babylon.max.js 4.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883
  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. this._loadVertexShader(vertexSource, function (vertexCode) {
  157. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  158. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  159. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  160. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  161. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  162. if (baseName) {
  163. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  164. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  165. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  166. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  167. }
  168. else {
  169. _this._vertexSourceCode = migratedVertexCode;
  170. _this._fragmentSourceCode = migratedFragmentCode;
  171. }
  172. _this._prepareEffect();
  173. });
  174. });
  175. });
  176. });
  177. });
  178. });
  179. }
  180. Object.defineProperty(Effect.prototype, "key", {
  181. get: function () {
  182. return this._key;
  183. },
  184. enumerable: true,
  185. configurable: true
  186. });
  187. // Properties
  188. Effect.prototype.isReady = function () {
  189. return this._isReady;
  190. };
  191. Effect.prototype.getEngine = function () {
  192. return this._engine;
  193. };
  194. Effect.prototype.getProgram = function () {
  195. return this._program;
  196. };
  197. Effect.prototype.getAttributesNames = function () {
  198. return this._attributesNames;
  199. };
  200. Effect.prototype.getAttributeLocation = function (index) {
  201. return this._attributes[index];
  202. };
  203. Effect.prototype.getAttributeLocationByName = function (name) {
  204. var index = this._attributesNames.indexOf(name);
  205. return this._attributes[index];
  206. };
  207. Effect.prototype.getAttributesCount = function () {
  208. return this._attributes.length;
  209. };
  210. Effect.prototype.getUniformIndex = function (uniformName) {
  211. return this._uniformsNames.indexOf(uniformName);
  212. };
  213. Effect.prototype.getUniform = function (uniformName) {
  214. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  215. };
  216. Effect.prototype.getSamplers = function () {
  217. return this._samplers;
  218. };
  219. Effect.prototype.getCompilationError = function () {
  220. return this._compilationError;
  221. };
  222. // Methods
  223. Effect.prototype.executeWhenCompiled = function (func) {
  224. if (this.isReady()) {
  225. func(this);
  226. return;
  227. }
  228. this.onCompileObservable.add(function (effect) {
  229. func(effect);
  230. });
  231. };
  232. Effect.prototype._loadVertexShader = function (vertex, callback) {
  233. if (BABYLON.Tools.IsWindowObjectExist()) {
  234. // DOM element ?
  235. if (vertex instanceof HTMLElement) {
  236. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  237. callback(vertexCode);
  238. return;
  239. }
  240. }
  241. // Base64 encoded ?
  242. if (vertex.substr(0, 7) === "base64:") {
  243. var vertexBinary = window.atob(vertex.substr(7));
  244. callback(vertexBinary);
  245. return;
  246. }
  247. // Is in local store ?
  248. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  249. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  250. return;
  251. }
  252. var vertexShaderUrl;
  253. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  254. vertexShaderUrl = vertex;
  255. }
  256. else {
  257. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  258. }
  259. // Vertex shader
  260. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  261. };
  262. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  263. if (BABYLON.Tools.IsWindowObjectExist()) {
  264. // DOM element ?
  265. if (fragment instanceof HTMLElement) {
  266. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  267. callback(fragmentCode);
  268. return;
  269. }
  270. }
  271. // Base64 encoded ?
  272. if (fragment.substr(0, 7) === "base64:") {
  273. var fragmentBinary = window.atob(fragment.substr(7));
  274. callback(fragmentBinary);
  275. return;
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  280. return;
  281. }
  282. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  283. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  284. return;
  285. }
  286. var fragmentShaderUrl;
  287. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  288. fragmentShaderUrl = fragment;
  289. }
  290. else {
  291. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  292. }
  293. // Fragment shader
  294. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  295. };
  296. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  297. // Rebuild shaders source code
  298. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  299. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  300. vertexCode = prefix + vertexCode;
  301. fragmentCode = prefix + fragmentCode;
  302. // Number lines of shaders source code
  303. var i = 2;
  304. var regex = /\n/gm;
  305. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. i = 2;
  307. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  308. // Dump shaders name and formatted source code
  309. if (this.name.vertexElement) {
  310. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  311. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  312. }
  313. else if (this.name.vertex) {
  314. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  315. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  316. }
  317. else {
  318. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  319. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  320. }
  321. };
  322. ;
  323. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  324. var preparedSourceCode = this._processPrecision(sourceCode);
  325. if (this._engine.webGLVersion == 1) {
  326. callback(preparedSourceCode);
  327. return;
  328. }
  329. // Already converted
  330. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  331. callback(preparedSourceCode.replace("#version 300 es", ""));
  332. return;
  333. }
  334. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  335. // Remove extensions
  336. // #extension GL_OES_standard_derivatives : enable
  337. // #extension GL_EXT_shader_texture_lod : enable
  338. // #extension GL_EXT_frag_depth : enable
  339. // #extension GL_EXT_draw_buffers : require
  340. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  341. var result = preparedSourceCode.replace(regex, "");
  342. // Migrate to GLSL v300
  343. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  344. result = result.replace(/attribute[ \t]/g, "in ");
  345. result = result.replace(/[ \t]attribute/g, " in");
  346. if (isFragment) {
  347. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  348. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  349. result = result.replace(/texture2D\s*\(/g, "texture(");
  350. result = result.replace(/textureCube\s*\(/g, "texture(");
  351. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  352. result = result.replace(/gl_FragColor/g, "glFragColor");
  353. result = result.replace(/gl_FragData/g, "glFragData");
  354. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  355. }
  356. callback(result);
  357. };
  358. Effect.prototype._processIncludes = function (sourceCode, callback) {
  359. var _this = this;
  360. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  361. var match = regex.exec(sourceCode);
  362. var returnValue = new String(sourceCode);
  363. while (match != null) {
  364. var includeFile = match[1];
  365. // Uniform declaration
  366. if (includeFile.indexOf("__decl__") !== -1) {
  367. includeFile = includeFile.replace(/__decl__/, "");
  368. if (this._engine.supportsUniformBuffers) {
  369. includeFile = includeFile.replace(/Vertex/, "Ubo");
  370. includeFile = includeFile.replace(/Fragment/, "Ubo");
  371. }
  372. includeFile = includeFile + "Declaration";
  373. }
  374. if (Effect.IncludesShadersStore[includeFile]) {
  375. // Substitution
  376. var includeContent = Effect.IncludesShadersStore[includeFile];
  377. if (match[2]) {
  378. var splits = match[3].split(",");
  379. for (var index = 0; index < splits.length; index += 2) {
  380. var source = new RegExp(splits[index], "g");
  381. var dest = splits[index + 1];
  382. includeContent = includeContent.replace(source, dest);
  383. }
  384. }
  385. if (match[4]) {
  386. var indexString = match[5];
  387. if (indexString.indexOf("..") !== -1) {
  388. var indexSplits = indexString.split("..");
  389. var minIndex = parseInt(indexSplits[0]);
  390. var maxIndex = parseInt(indexSplits[1]);
  391. var sourceIncludeContent = includeContent.slice(0);
  392. includeContent = "";
  393. if (isNaN(maxIndex)) {
  394. maxIndex = this._indexParameters[indexSplits[1]];
  395. }
  396. for (var i = minIndex; i < maxIndex; i++) {
  397. if (!this._engine.supportsUniformBuffers) {
  398. // Ubo replacement
  399. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  400. return p1 + "{X}";
  401. });
  402. }
  403. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  404. }
  405. }
  406. else {
  407. if (!this._engine.supportsUniformBuffers) {
  408. // Ubo replacement
  409. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  410. return p1 + "{X}";
  411. });
  412. }
  413. includeContent = includeContent.replace(/\{X\}/g, indexString);
  414. }
  415. }
  416. // Replace
  417. returnValue = returnValue.replace(match[0], includeContent);
  418. }
  419. else {
  420. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  421. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  422. Effect.IncludesShadersStore[includeFile] = fileContent;
  423. _this._processIncludes(returnValue, callback);
  424. });
  425. return;
  426. }
  427. match = regex.exec(sourceCode);
  428. }
  429. callback(returnValue);
  430. };
  431. Effect.prototype._processPrecision = function (source) {
  432. if (source.indexOf("precision highp float") === -1) {
  433. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  434. source = "precision mediump float;\n" + source;
  435. }
  436. else {
  437. source = "precision highp float;\n" + source;
  438. }
  439. }
  440. else {
  441. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  442. source = source.replace("precision highp float", "precision mediump float");
  443. }
  444. }
  445. return source;
  446. };
  447. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  448. var _this = this;
  449. this._isReady = false;
  450. this._vertexSourceCodeOverride = vertexSourceCode;
  451. this._fragmentSourceCodeOverride = fragmentSourceCode;
  452. this.onError = function (effect, error) {
  453. if (onError) {
  454. onError(error);
  455. }
  456. };
  457. this.onCompiled = function () {
  458. var scenes = _this.getEngine().scenes;
  459. for (var i = 0; i < scenes.length; i++) {
  460. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  461. }
  462. if (onCompiled) {
  463. onCompiled(_this._program);
  464. }
  465. };
  466. this._fallbacks = null;
  467. this._prepareEffect();
  468. };
  469. Effect.prototype.getSpecificUniformLocations = function (names) {
  470. var engine = this._engine;
  471. return engine.getUniforms(this._program, names);
  472. };
  473. Effect.prototype._prepareEffect = function () {
  474. var attributesNames = this._attributesNames;
  475. var defines = this.defines;
  476. var fallbacks = this._fallbacks;
  477. this._valueCache = {};
  478. var previousProgram = this._program;
  479. try {
  480. var engine = this._engine;
  481. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  482. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  483. }
  484. else {
  485. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  486. }
  487. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  488. if (engine.supportsUniformBuffers) {
  489. for (var name in this._uniformBuffersNames) {
  490. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  491. }
  492. }
  493. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  494. this._attributes = engine.getAttributes(this._program, attributesNames);
  495. var index;
  496. for (index = 0; index < this._samplers.length; index++) {
  497. var sampler = this.getUniform(this._samplers[index]);
  498. if (sampler == null) {
  499. this._samplers.splice(index, 1);
  500. index--;
  501. }
  502. }
  503. engine.bindSamplers(this);
  504. this._compilationError = "";
  505. this._isReady = true;
  506. if (this.onCompiled) {
  507. this.onCompiled(this);
  508. }
  509. this.onCompileObservable.notifyObservers(this);
  510. this.onCompileObservable.clear();
  511. // Unbind mesh reference in fallbacks
  512. if (this._fallbacks) {
  513. this._fallbacks.unBindMesh();
  514. }
  515. if (previousProgram) {
  516. this.getEngine()._deleteProgram(previousProgram);
  517. }
  518. }
  519. catch (e) {
  520. this._compilationError = e.message;
  521. // Let's go through fallbacks then
  522. BABYLON.Tools.Error("Unable to compile effect:");
  523. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  524. return " " + uniform;
  525. }));
  526. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  527. return " " + attribute;
  528. }));
  529. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  530. BABYLON.Tools.Error("Error: " + this._compilationError);
  531. if (previousProgram) {
  532. this._program = previousProgram;
  533. this._isReady = true;
  534. if (this.onError) {
  535. this.onError(this, this._compilationError);
  536. }
  537. this.onErrorObservable.notifyObservers(this);
  538. }
  539. if (fallbacks && fallbacks.isMoreFallbacks) {
  540. BABYLON.Tools.Error("Trying next fallback.");
  541. this.defines = fallbacks.reduce(this.defines);
  542. this._prepareEffect();
  543. }
  544. else {
  545. if (this.onError) {
  546. this.onError(this, this._compilationError);
  547. }
  548. this.onErrorObservable.notifyObservers(this);
  549. this.onErrorObservable.clear();
  550. // Unbind mesh reference in fallbacks
  551. if (this._fallbacks) {
  552. this._fallbacks.unBindMesh();
  553. }
  554. }
  555. }
  556. };
  557. Object.defineProperty(Effect.prototype, "isSupported", {
  558. get: function () {
  559. return this._compilationError === "";
  560. },
  561. enumerable: true,
  562. configurable: true
  563. });
  564. Effect.prototype._bindTexture = function (channel, texture) {
  565. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  566. };
  567. Effect.prototype.setTexture = function (channel, texture) {
  568. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  569. };
  570. Effect.prototype.setTextureArray = function (channel, textures) {
  571. if (this._samplers.indexOf(channel + "Ex") === -1) {
  572. var initialPos = this._samplers.indexOf(channel);
  573. for (var index = 1; index < textures.length; index++) {
  574. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  575. }
  576. }
  577. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  578. };
  579. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  580. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  581. };
  582. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  583. var cache = this._valueCache[uniformName];
  584. var flag = matrix.updateFlag;
  585. if (cache !== undefined && cache === flag) {
  586. return false;
  587. }
  588. this._valueCache[uniformName] = flag;
  589. return true;
  590. };
  591. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  592. var cache = this._valueCache[uniformName];
  593. if (!cache) {
  594. cache = [x, y];
  595. this._valueCache[uniformName] = cache;
  596. return true;
  597. }
  598. var changed = false;
  599. if (cache[0] !== x) {
  600. cache[0] = x;
  601. changed = true;
  602. }
  603. if (cache[1] !== y) {
  604. cache[1] = y;
  605. changed = true;
  606. }
  607. return changed;
  608. };
  609. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  610. var cache = this._valueCache[uniformName];
  611. if (!cache) {
  612. cache = [x, y, z];
  613. this._valueCache[uniformName] = cache;
  614. return true;
  615. }
  616. var changed = false;
  617. if (cache[0] !== x) {
  618. cache[0] = x;
  619. changed = true;
  620. }
  621. if (cache[1] !== y) {
  622. cache[1] = y;
  623. changed = true;
  624. }
  625. if (cache[2] !== z) {
  626. cache[2] = z;
  627. changed = true;
  628. }
  629. return changed;
  630. };
  631. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  632. var cache = this._valueCache[uniformName];
  633. if (!cache) {
  634. cache = [x, y, z, w];
  635. this._valueCache[uniformName] = cache;
  636. return true;
  637. }
  638. var changed = false;
  639. if (cache[0] !== x) {
  640. cache[0] = x;
  641. changed = true;
  642. }
  643. if (cache[1] !== y) {
  644. cache[1] = y;
  645. changed = true;
  646. }
  647. if (cache[2] !== z) {
  648. cache[2] = z;
  649. changed = true;
  650. }
  651. if (cache[3] !== w) {
  652. cache[3] = w;
  653. changed = true;
  654. }
  655. return changed;
  656. };
  657. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  658. var bufferName = this._uniformBuffersNames[name];
  659. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  660. return;
  661. }
  662. Effect._baseCache[bufferName] = buffer;
  663. this._engine.bindUniformBufferBase(buffer, bufferName);
  664. };
  665. Effect.prototype.bindUniformBlock = function (blockName, index) {
  666. this._engine.bindUniformBlock(this._program, blockName, index);
  667. };
  668. Effect.prototype.setInt = function (uniformName, value) {
  669. var cache = this._valueCache[uniformName];
  670. if (cache !== undefined && cache === value)
  671. return this;
  672. this._valueCache[uniformName] = value;
  673. this._engine.setInt(this.getUniform(uniformName), value);
  674. return this;
  675. };
  676. Effect.prototype.setIntArray = function (uniformName, array) {
  677. this._valueCache[uniformName] = null;
  678. this._engine.setIntArray(this.getUniform(uniformName), array);
  679. return this;
  680. };
  681. Effect.prototype.setIntArray2 = function (uniformName, array) {
  682. this._valueCache[uniformName] = null;
  683. this._engine.setIntArray2(this.getUniform(uniformName), array);
  684. return this;
  685. };
  686. Effect.prototype.setIntArray3 = function (uniformName, array) {
  687. this._valueCache[uniformName] = null;
  688. this._engine.setIntArray3(this.getUniform(uniformName), array);
  689. return this;
  690. };
  691. Effect.prototype.setIntArray4 = function (uniformName, array) {
  692. this._valueCache[uniformName] = null;
  693. this._engine.setIntArray4(this.getUniform(uniformName), array);
  694. return this;
  695. };
  696. Effect.prototype.setFloatArray = function (uniformName, array) {
  697. this._valueCache[uniformName] = null;
  698. this._engine.setFloatArray(this.getUniform(uniformName), array);
  699. return this;
  700. };
  701. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  702. this._valueCache[uniformName] = null;
  703. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  704. return this;
  705. };
  706. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  707. this._valueCache[uniformName] = null;
  708. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  709. return this;
  710. };
  711. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  712. this._valueCache[uniformName] = null;
  713. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  714. return this;
  715. };
  716. Effect.prototype.setArray = function (uniformName, array) {
  717. this._valueCache[uniformName] = null;
  718. this._engine.setArray(this.getUniform(uniformName), array);
  719. return this;
  720. };
  721. Effect.prototype.setArray2 = function (uniformName, array) {
  722. this._valueCache[uniformName] = null;
  723. this._engine.setArray2(this.getUniform(uniformName), array);
  724. return this;
  725. };
  726. Effect.prototype.setArray3 = function (uniformName, array) {
  727. this._valueCache[uniformName] = null;
  728. this._engine.setArray3(this.getUniform(uniformName), array);
  729. return this;
  730. };
  731. Effect.prototype.setArray4 = function (uniformName, array) {
  732. this._valueCache[uniformName] = null;
  733. this._engine.setArray4(this.getUniform(uniformName), array);
  734. return this;
  735. };
  736. Effect.prototype.setMatrices = function (uniformName, matrices) {
  737. if (!matrices) {
  738. return this;
  739. }
  740. this._valueCache[uniformName] = null;
  741. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  742. return this;
  743. };
  744. Effect.prototype.setMatrix = function (uniformName, matrix) {
  745. if (this._cacheMatrix(uniformName, matrix)) {
  746. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  747. }
  748. return this;
  749. };
  750. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  751. this._valueCache[uniformName] = null;
  752. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  753. return this;
  754. };
  755. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  756. this._valueCache[uniformName] = null;
  757. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  758. return this;
  759. };
  760. Effect.prototype.setFloat = function (uniformName, value) {
  761. var cache = this._valueCache[uniformName];
  762. if (cache !== undefined && cache === value)
  763. return this;
  764. this._valueCache[uniformName] = value;
  765. this._engine.setFloat(this.getUniform(uniformName), value);
  766. return this;
  767. };
  768. Effect.prototype.setBool = function (uniformName, bool) {
  769. var cache = this._valueCache[uniformName];
  770. if (cache !== undefined && cache === bool)
  771. return this;
  772. this._valueCache[uniformName] = bool;
  773. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  774. return this;
  775. };
  776. Effect.prototype.setVector2 = function (uniformName, vector2) {
  777. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  778. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  783. if (this._cacheFloat2(uniformName, x, y)) {
  784. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector3 = function (uniformName, vector3) {
  789. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  790. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  795. if (this._cacheFloat3(uniformName, x, y, z)) {
  796. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setVector4 = function (uniformName, vector4) {
  801. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  802. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  807. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  808. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  809. }
  810. return this;
  811. };
  812. Effect.prototype.setColor3 = function (uniformName, color3) {
  813. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  814. this._engine.setColor3(this.getUniform(uniformName), color3);
  815. }
  816. return this;
  817. };
  818. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  819. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  820. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  821. }
  822. return this;
  823. };
  824. Effect.ResetCache = function () {
  825. Effect._baseCache = {};
  826. };
  827. Effect._uniqueIdSeed = 0;
  828. Effect._baseCache = {};
  829. // Statics
  830. Effect.ShadersStore = {};
  831. Effect.IncludesShadersStore = {};
  832. return Effect;
  833. }());
  834. BABYLON.Effect = Effect;
  835. })(BABYLON || (BABYLON = {}));
  836. //# sourceMappingURL=babylon.effect.js.map
  837. //# sourceMappingURL=babylon.types.js.map
  838. var BABYLON;
  839. (function (BABYLON) {
  840. var KeyboardEventTypes = /** @class */ (function () {
  841. function KeyboardEventTypes() {
  842. }
  843. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  844. get: function () {
  845. return KeyboardEventTypes._KEYDOWN;
  846. },
  847. enumerable: true,
  848. configurable: true
  849. });
  850. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  851. get: function () {
  852. return KeyboardEventTypes._KEYUP;
  853. },
  854. enumerable: true,
  855. configurable: true
  856. });
  857. KeyboardEventTypes._KEYDOWN = 0x01;
  858. KeyboardEventTypes._KEYUP = 0x02;
  859. return KeyboardEventTypes;
  860. }());
  861. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  862. var KeyboardInfo = /** @class */ (function () {
  863. function KeyboardInfo(type, event) {
  864. this.type = type;
  865. this.event = event;
  866. }
  867. return KeyboardInfo;
  868. }());
  869. BABYLON.KeyboardInfo = KeyboardInfo;
  870. /**
  871. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  872. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  873. */
  874. var KeyboardInfoPre = /** @class */ (function (_super) {
  875. __extends(KeyboardInfoPre, _super);
  876. function KeyboardInfoPre(type, event) {
  877. var _this = _super.call(this, type, event) || this;
  878. _this.skipOnPointerObservable = false;
  879. return _this;
  880. }
  881. return KeyboardInfoPre;
  882. }(KeyboardInfo));
  883. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  884. })(BABYLON || (BABYLON = {}));
  885. //# sourceMappingURL=babylon.keyboardEvents.js.map
  886. var BABYLON;
  887. (function (BABYLON) {
  888. var PointerEventTypes = /** @class */ (function () {
  889. function PointerEventTypes() {
  890. }
  891. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  892. get: function () {
  893. return PointerEventTypes._POINTERDOWN;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  899. get: function () {
  900. return PointerEventTypes._POINTERUP;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  906. get: function () {
  907. return PointerEventTypes._POINTERMOVE;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  913. get: function () {
  914. return PointerEventTypes._POINTERWHEEL;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  920. get: function () {
  921. return PointerEventTypes._POINTERPICK;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  927. get: function () {
  928. return PointerEventTypes._POINTERTAP;
  929. },
  930. enumerable: true,
  931. configurable: true
  932. });
  933. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  934. get: function () {
  935. return PointerEventTypes._POINTERDOUBLETAP;
  936. },
  937. enumerable: true,
  938. configurable: true
  939. });
  940. PointerEventTypes._POINTERDOWN = 0x01;
  941. PointerEventTypes._POINTERUP = 0x02;
  942. PointerEventTypes._POINTERMOVE = 0x04;
  943. PointerEventTypes._POINTERWHEEL = 0x08;
  944. PointerEventTypes._POINTERPICK = 0x10;
  945. PointerEventTypes._POINTERTAP = 0x20;
  946. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  947. return PointerEventTypes;
  948. }());
  949. BABYLON.PointerEventTypes = PointerEventTypes;
  950. var PointerInfoBase = /** @class */ (function () {
  951. function PointerInfoBase(type, event) {
  952. this.type = type;
  953. this.event = event;
  954. }
  955. return PointerInfoBase;
  956. }());
  957. BABYLON.PointerInfoBase = PointerInfoBase;
  958. /**
  959. * This class is used to store pointer related info for the onPrePointerObservable event.
  960. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  961. */
  962. var PointerInfoPre = /** @class */ (function (_super) {
  963. __extends(PointerInfoPre, _super);
  964. function PointerInfoPre(type, event, localX, localY) {
  965. var _this = _super.call(this, type, event) || this;
  966. _this.skipOnPointerObservable = false;
  967. _this.localPosition = new BABYLON.Vector2(localX, localY);
  968. return _this;
  969. }
  970. return PointerInfoPre;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfoPre = PointerInfoPre;
  973. /**
  974. * This type contains all the data related to a pointer event in Babylon.js.
  975. * 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.
  976. */
  977. var PointerInfo = /** @class */ (function (_super) {
  978. __extends(PointerInfo, _super);
  979. function PointerInfo(type, event, pickInfo) {
  980. var _this = _super.call(this, type, event) || this;
  981. _this.pickInfo = pickInfo;
  982. return _this;
  983. }
  984. return PointerInfo;
  985. }(PointerInfoBase));
  986. BABYLON.PointerInfo = PointerInfo;
  987. })(BABYLON || (BABYLON = {}));
  988. //# sourceMappingURL=babylon.pointerEvents.js.map
  989. var BABYLON;
  990. (function (BABYLON) {
  991. BABYLON.ToGammaSpace = 1 / 2.2;
  992. BABYLON.ToLinearSpace = 2.2;
  993. BABYLON.Epsilon = 0.001;
  994. var Color3 = /** @class */ (function () {
  995. /**
  996. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  997. */
  998. function Color3(r, g, b) {
  999. if (r === void 0) { r = 0; }
  1000. if (g === void 0) { g = 0; }
  1001. if (b === void 0) { b = 0; }
  1002. this.r = r;
  1003. this.g = g;
  1004. this.b = b;
  1005. }
  1006. /**
  1007. * Returns a string with the Color3 current values.
  1008. */
  1009. Color3.prototype.toString = function () {
  1010. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1011. };
  1012. /**
  1013. * Returns the string "Color3".
  1014. */
  1015. Color3.prototype.getClassName = function () {
  1016. return "Color3";
  1017. };
  1018. /**
  1019. * Returns the Color3 hash code.
  1020. */
  1021. Color3.prototype.getHashCode = function () {
  1022. var hash = this.r || 0;
  1023. hash = (hash * 397) ^ (this.g || 0);
  1024. hash = (hash * 397) ^ (this.b || 0);
  1025. return hash;
  1026. };
  1027. // Operators
  1028. /**
  1029. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1030. * Returns the Color3.
  1031. */
  1032. Color3.prototype.toArray = function (array, index) {
  1033. if (index === undefined) {
  1034. index = 0;
  1035. }
  1036. array[index] = this.r;
  1037. array[index + 1] = this.g;
  1038. array[index + 2] = this.b;
  1039. return this;
  1040. };
  1041. /**
  1042. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1043. */
  1044. Color3.prototype.toColor4 = function (alpha) {
  1045. if (alpha === void 0) { alpha = 1; }
  1046. return new Color4(this.r, this.g, this.b, alpha);
  1047. };
  1048. /**
  1049. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1050. */
  1051. Color3.prototype.asArray = function () {
  1052. var result = new Array();
  1053. this.toArray(result, 0);
  1054. return result;
  1055. };
  1056. /**
  1057. * Returns the luminance value (float).
  1058. */
  1059. Color3.prototype.toLuminance = function () {
  1060. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1061. };
  1062. /**
  1063. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1064. * Returns this new object.
  1065. */
  1066. Color3.prototype.multiply = function (otherColor) {
  1067. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1068. };
  1069. /**
  1070. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1071. * Returns the current Color3.
  1072. */
  1073. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1074. result.r = this.r * otherColor.r;
  1075. result.g = this.g * otherColor.g;
  1076. result.b = this.b * otherColor.b;
  1077. return this;
  1078. };
  1079. /**
  1080. * Boolean : True if the rgb values are equal to the passed ones.
  1081. */
  1082. Color3.prototype.equals = function (otherColor) {
  1083. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1084. };
  1085. /**
  1086. * Boolean : True if the rgb values are equal to the passed ones.
  1087. */
  1088. Color3.prototype.equalsFloats = function (r, g, b) {
  1089. return this.r === r && this.g === g && this.b === b;
  1090. };
  1091. /**
  1092. * Multiplies in place each rgb value by scale.
  1093. * Returns the updated Color3.
  1094. */
  1095. Color3.prototype.scale = function (scale) {
  1096. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1097. };
  1098. /**
  1099. * Multiplies the rgb values by scale and stores the result into "result".
  1100. * Returns the unmodified current Color3.
  1101. */
  1102. Color3.prototype.scaleToRef = function (scale, result) {
  1103. result.r = this.r * scale;
  1104. result.g = this.g * scale;
  1105. result.b = this.b * scale;
  1106. return this;
  1107. };
  1108. /**
  1109. * Clamps the rgb values by the min and max values and stores the result into "result".
  1110. * Returns the unmodified current Color3.
  1111. * @param min - minimum clamping value. Defaults to 0
  1112. * @param max - maximum clamping value. Defaults to 1
  1113. * @param result - color to store the result into.
  1114. * @returns - the original Color3
  1115. */
  1116. Color3.prototype.clampToRef = function (min, max, result) {
  1117. if (min === void 0) { min = 0; }
  1118. if (max === void 0) { max = 1; }
  1119. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1120. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1121. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1122. return this;
  1123. };
  1124. /**
  1125. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1126. */
  1127. Color3.prototype.add = function (otherColor) {
  1128. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1129. };
  1130. /**
  1131. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1132. * Returns the unmodified current Color3.
  1133. */
  1134. Color3.prototype.addToRef = function (otherColor, result) {
  1135. result.r = this.r + otherColor.r;
  1136. result.g = this.g + otherColor.g;
  1137. result.b = this.b + otherColor.b;
  1138. return this;
  1139. };
  1140. /**
  1141. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1142. */
  1143. Color3.prototype.subtract = function (otherColor) {
  1144. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1145. };
  1146. /**
  1147. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1148. * Returns the unmodified current Color3.
  1149. */
  1150. Color3.prototype.subtractToRef = function (otherColor, result) {
  1151. result.r = this.r - otherColor.r;
  1152. result.g = this.g - otherColor.g;
  1153. result.b = this.b - otherColor.b;
  1154. return this;
  1155. };
  1156. /**
  1157. * Returns a new Color3 copied the current one.
  1158. */
  1159. Color3.prototype.clone = function () {
  1160. return new Color3(this.r, this.g, this.b);
  1161. };
  1162. /**
  1163. * Copies the rgb values from the source in the current Color3.
  1164. * Returns the updated Color3.
  1165. */
  1166. Color3.prototype.copyFrom = function (source) {
  1167. this.r = source.r;
  1168. this.g = source.g;
  1169. this.b = source.b;
  1170. return this;
  1171. };
  1172. /**
  1173. * Updates the Color3 rgb values from the passed floats.
  1174. * Returns the Color3.
  1175. */
  1176. Color3.prototype.copyFromFloats = function (r, g, b) {
  1177. this.r = r;
  1178. this.g = g;
  1179. this.b = b;
  1180. return this;
  1181. };
  1182. /**
  1183. * Updates the Color3 rgb values from the passed floats.
  1184. * Returns the Color3.
  1185. */
  1186. Color3.prototype.set = function (r, g, b) {
  1187. return this.copyFromFloats(r, g, b);
  1188. };
  1189. /**
  1190. * Returns the Color3 hexadecimal code as a string.
  1191. */
  1192. Color3.prototype.toHexString = function () {
  1193. var intR = (this.r * 255) | 0;
  1194. var intG = (this.g * 255) | 0;
  1195. var intB = (this.b * 255) | 0;
  1196. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1197. };
  1198. /**
  1199. * Returns a new Color3 converted to linear space.
  1200. */
  1201. Color3.prototype.toLinearSpace = function () {
  1202. var convertedColor = new Color3();
  1203. this.toLinearSpaceToRef(convertedColor);
  1204. return convertedColor;
  1205. };
  1206. /**
  1207. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1208. * Returns the unmodified Color3.
  1209. */
  1210. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1211. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1212. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1213. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Color3 converted to gamma space.
  1218. */
  1219. Color3.prototype.toGammaSpace = function () {
  1220. var convertedColor = new Color3();
  1221. this.toGammaSpaceToRef(convertedColor);
  1222. return convertedColor;
  1223. };
  1224. /**
  1225. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1226. * Returns the unmodified Color3.
  1227. */
  1228. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1229. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1230. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1231. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1232. return this;
  1233. };
  1234. // Statics
  1235. /**
  1236. * Creates a new Color3 from the string containing valid hexadecimal values.
  1237. */
  1238. Color3.FromHexString = function (hex) {
  1239. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1240. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1241. return new Color3(0, 0, 0);
  1242. }
  1243. var r = parseInt(hex.substring(1, 3), 16);
  1244. var g = parseInt(hex.substring(3, 5), 16);
  1245. var b = parseInt(hex.substring(5, 7), 16);
  1246. return Color3.FromInts(r, g, b);
  1247. };
  1248. /**
  1249. * Creates a new Vector3 from the startind index of the passed array.
  1250. */
  1251. Color3.FromArray = function (array, offset) {
  1252. if (offset === void 0) { offset = 0; }
  1253. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1254. };
  1255. /**
  1256. * Creates a new Color3 from integer values ( < 256).
  1257. */
  1258. Color3.FromInts = function (r, g, b) {
  1259. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1260. };
  1261. /**
  1262. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1263. */
  1264. Color3.Lerp = function (start, end, amount) {
  1265. var r = start.r + ((end.r - start.r) * amount);
  1266. var g = start.g + ((end.g - start.g) * amount);
  1267. var b = start.b + ((end.b - start.b) * amount);
  1268. return new Color3(r, g, b);
  1269. };
  1270. Color3.Red = function () { return new Color3(1, 0, 0); };
  1271. Color3.Green = function () { return new Color3(0, 1, 0); };
  1272. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1273. Color3.Black = function () { return new Color3(0, 0, 0); };
  1274. Color3.White = function () { return new Color3(1, 1, 1); };
  1275. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1276. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1277. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1278. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1279. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1280. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1281. return Color3;
  1282. }());
  1283. BABYLON.Color3 = Color3;
  1284. var Color4 = /** @class */ (function () {
  1285. /**
  1286. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1287. */
  1288. function Color4(r, g, b, a) {
  1289. if (r === void 0) { r = 0; }
  1290. if (g === void 0) { g = 0; }
  1291. if (b === void 0) { b = 0; }
  1292. if (a === void 0) { a = 1; }
  1293. this.r = r;
  1294. this.g = g;
  1295. this.b = b;
  1296. this.a = a;
  1297. }
  1298. // Operators
  1299. /**
  1300. * Adds in place the passed Color4 values to the current Color4.
  1301. * Returns the updated Color4.
  1302. */
  1303. Color4.prototype.addInPlace = function (right) {
  1304. this.r += right.r;
  1305. this.g += right.g;
  1306. this.b += right.b;
  1307. this.a += right.a;
  1308. return this;
  1309. };
  1310. /**
  1311. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1312. */
  1313. Color4.prototype.asArray = function () {
  1314. var result = new Array();
  1315. this.toArray(result, 0);
  1316. return result;
  1317. };
  1318. /**
  1319. * Stores from the starting index in the passed array the Color4 successive values.
  1320. * Returns the Color4.
  1321. */
  1322. Color4.prototype.toArray = function (array, index) {
  1323. if (index === undefined) {
  1324. index = 0;
  1325. }
  1326. array[index] = this.r;
  1327. array[index + 1] = this.g;
  1328. array[index + 2] = this.b;
  1329. array[index + 3] = this.a;
  1330. return this;
  1331. };
  1332. /**
  1333. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1334. */
  1335. Color4.prototype.add = function (right) {
  1336. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1337. };
  1338. /**
  1339. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1340. */
  1341. Color4.prototype.subtract = function (right) {
  1342. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1343. };
  1344. /**
  1345. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1346. * Returns the Color4.
  1347. */
  1348. Color4.prototype.subtractToRef = function (right, result) {
  1349. result.r = this.r - right.r;
  1350. result.g = this.g - right.g;
  1351. result.b = this.b - right.b;
  1352. result.a = this.a - right.a;
  1353. return this;
  1354. };
  1355. /**
  1356. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1357. */
  1358. Color4.prototype.scale = function (scale) {
  1359. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1360. };
  1361. /**
  1362. * Multiplies the current Color4 values by scale and stores the result in "result".
  1363. * Returns the Color4.
  1364. */
  1365. Color4.prototype.scaleToRef = function (scale, result) {
  1366. result.r = this.r * scale;
  1367. result.g = this.g * scale;
  1368. result.b = this.b * scale;
  1369. result.a = this.a * scale;
  1370. return this;
  1371. };
  1372. /**
  1373. * Clamps the rgb values by the min and max values and stores the result into "result".
  1374. * Returns the unmodified current Color4.
  1375. * @param min - minimum clamping value. Defaults to 0
  1376. * @param max - maximum clamping value. Defaults to 1
  1377. * @param result - color to store the result into.
  1378. * @returns - the original Color4
  1379. */
  1380. Color4.prototype.clampToRef = function (min, max, result) {
  1381. if (min === void 0) { min = 0; }
  1382. if (max === void 0) { max = 1; }
  1383. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1384. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1385. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1386. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1387. return this;
  1388. };
  1389. /**
  1390. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1391. * @param color The Color4 (RGBA) value to multiply by
  1392. * @returns A new Color4.
  1393. */
  1394. Color4.prototype.multiply = function (color) {
  1395. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1396. };
  1397. /**
  1398. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1399. * @param color The Color4 (RGBA) value to multiply by
  1400. * @param result The Color4 (RGBA) to fill the result in
  1401. * @returns the result Color4.
  1402. */
  1403. Color4.prototype.multiplyToRef = function (color, result) {
  1404. result.r = this.r * color.r;
  1405. result.g = this.g * color.g;
  1406. result.b = this.b * color.b;
  1407. result.a = this.a * color.a;
  1408. return result;
  1409. };
  1410. /**
  1411. * Returns a string with the Color4 values.
  1412. */
  1413. Color4.prototype.toString = function () {
  1414. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1415. };
  1416. /**
  1417. * Returns the string "Color4"
  1418. */
  1419. Color4.prototype.getClassName = function () {
  1420. return "Color4";
  1421. };
  1422. /**
  1423. * Return the Color4 hash code as a number.
  1424. */
  1425. Color4.prototype.getHashCode = function () {
  1426. var hash = this.r || 0;
  1427. hash = (hash * 397) ^ (this.g || 0);
  1428. hash = (hash * 397) ^ (this.b || 0);
  1429. hash = (hash * 397) ^ (this.a || 0);
  1430. return hash;
  1431. };
  1432. /**
  1433. * Creates a new Color4 copied from the current one.
  1434. */
  1435. Color4.prototype.clone = function () {
  1436. return new Color4(this.r, this.g, this.b, this.a);
  1437. };
  1438. /**
  1439. * Copies the passed Color4 values into the current one.
  1440. * Returns the updated Color4.
  1441. */
  1442. Color4.prototype.copyFrom = function (source) {
  1443. this.r = source.r;
  1444. this.g = source.g;
  1445. this.b = source.b;
  1446. this.a = source.a;
  1447. return this;
  1448. };
  1449. /**
  1450. * Copies the passed float values into the current one.
  1451. * Returns the updated Color4.
  1452. */
  1453. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1454. this.r = r;
  1455. this.g = g;
  1456. this.b = b;
  1457. this.a = a;
  1458. return this;
  1459. };
  1460. /**
  1461. * Copies the passed float values into the current one.
  1462. * Returns the updated Color4.
  1463. */
  1464. Color4.prototype.set = function (r, g, b, a) {
  1465. return this.copyFromFloats(r, g, b, a);
  1466. };
  1467. /**
  1468. * Returns a string containing the hexadecimal Color4 code.
  1469. */
  1470. Color4.prototype.toHexString = function () {
  1471. var intR = (this.r * 255) | 0;
  1472. var intG = (this.g * 255) | 0;
  1473. var intB = (this.b * 255) | 0;
  1474. var intA = (this.a * 255) | 0;
  1475. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1476. };
  1477. /**
  1478. * Returns a new Color4 converted to linear space.
  1479. */
  1480. Color4.prototype.toLinearSpace = function () {
  1481. var convertedColor = new Color4();
  1482. this.toLinearSpaceToRef(convertedColor);
  1483. return convertedColor;
  1484. };
  1485. /**
  1486. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1487. * Returns the unmodified Color4.
  1488. */
  1489. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1490. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1491. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1492. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1493. convertedColor.a = this.a;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new Color4 converted to gamma space.
  1498. */
  1499. Color4.prototype.toGammaSpace = function () {
  1500. var convertedColor = new Color4();
  1501. this.toGammaSpaceToRef(convertedColor);
  1502. return convertedColor;
  1503. };
  1504. /**
  1505. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1506. * Returns the unmodified Color4.
  1507. */
  1508. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1509. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1510. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1511. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1512. convertedColor.a = this.a;
  1513. return this;
  1514. };
  1515. // Statics
  1516. /**
  1517. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1518. */
  1519. Color4.FromHexString = function (hex) {
  1520. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1521. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1522. return new Color4(0.0, 0.0, 0.0, 0.0);
  1523. }
  1524. var r = parseInt(hex.substring(1, 3), 16);
  1525. var g = parseInt(hex.substring(3, 5), 16);
  1526. var b = parseInt(hex.substring(5, 7), 16);
  1527. var a = parseInt(hex.substring(7, 9), 16);
  1528. return Color4.FromInts(r, g, b, a);
  1529. };
  1530. /**
  1531. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1532. */
  1533. Color4.Lerp = function (left, right, amount) {
  1534. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1535. Color4.LerpToRef(left, right, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1540. */
  1541. Color4.LerpToRef = function (left, right, amount, result) {
  1542. result.r = left.r + (right.r - left.r) * amount;
  1543. result.g = left.g + (right.g - left.g) * amount;
  1544. result.b = left.b + (right.b - left.b) * amount;
  1545. result.a = left.a + (right.a - left.a) * amount;
  1546. };
  1547. /**
  1548. * Creates a new Color4 from the starting index element of the passed array.
  1549. */
  1550. Color4.FromArray = function (array, offset) {
  1551. if (offset === void 0) { offset = 0; }
  1552. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1553. };
  1554. /**
  1555. * Creates a new Color4 from the passed integers ( < 256 ).
  1556. */
  1557. Color4.FromInts = function (r, g, b, a) {
  1558. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1559. };
  1560. Color4.CheckColors4 = function (colors, count) {
  1561. // Check if color3 was used
  1562. if (colors.length === count * 3) {
  1563. var colors4 = [];
  1564. for (var index = 0; index < colors.length; index += 3) {
  1565. var newIndex = (index / 3) * 4;
  1566. colors4[newIndex] = colors[index];
  1567. colors4[newIndex + 1] = colors[index + 1];
  1568. colors4[newIndex + 2] = colors[index + 2];
  1569. colors4[newIndex + 3] = 1.0;
  1570. }
  1571. return colors4;
  1572. }
  1573. return colors;
  1574. };
  1575. return Color4;
  1576. }());
  1577. BABYLON.Color4 = Color4;
  1578. var Vector2 = /** @class */ (function () {
  1579. /**
  1580. * Creates a new Vector2 from the passed x and y coordinates.
  1581. */
  1582. function Vector2(x, y) {
  1583. this.x = x;
  1584. this.y = y;
  1585. }
  1586. /**
  1587. * Returns a string with the Vector2 coordinates.
  1588. */
  1589. Vector2.prototype.toString = function () {
  1590. return "{X: " + this.x + " Y:" + this.y + "}";
  1591. };
  1592. /**
  1593. * Returns the string "Vector2"
  1594. */
  1595. Vector2.prototype.getClassName = function () {
  1596. return "Vector2";
  1597. };
  1598. /**
  1599. * Returns the Vector2 hash code as a number.
  1600. */
  1601. Vector2.prototype.getHashCode = function () {
  1602. var hash = this.x || 0;
  1603. hash = (hash * 397) ^ (this.y || 0);
  1604. return hash;
  1605. };
  1606. // Operators
  1607. /**
  1608. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1609. * Returns the Vector2.
  1610. */
  1611. Vector2.prototype.toArray = function (array, index) {
  1612. if (index === void 0) { index = 0; }
  1613. array[index] = this.x;
  1614. array[index + 1] = this.y;
  1615. return this;
  1616. };
  1617. /**
  1618. * Returns a new array with 2 elements : the Vector2 coordinates.
  1619. */
  1620. Vector2.prototype.asArray = function () {
  1621. var result = new Array();
  1622. this.toArray(result, 0);
  1623. return result;
  1624. };
  1625. /**
  1626. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1627. * Returns the updated Vector2.
  1628. */
  1629. Vector2.prototype.copyFrom = function (source) {
  1630. this.x = source.x;
  1631. this.y = source.y;
  1632. return this;
  1633. };
  1634. /**
  1635. * Sets the Vector2 coordinates with the passed floats.
  1636. * Returns the updated Vector2.
  1637. */
  1638. Vector2.prototype.copyFromFloats = function (x, y) {
  1639. this.x = x;
  1640. this.y = y;
  1641. return this;
  1642. };
  1643. /**
  1644. * Sets the Vector2 coordinates with the passed floats.
  1645. * Returns the updated Vector2.
  1646. */
  1647. Vector2.prototype.set = function (x, y) {
  1648. return this.copyFromFloats(x, y);
  1649. };
  1650. /**
  1651. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1652. */
  1653. Vector2.prototype.add = function (otherVector) {
  1654. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1655. };
  1656. /**
  1657. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1658. * Returns the Vector2.
  1659. */
  1660. Vector2.prototype.addToRef = function (otherVector, result) {
  1661. result.x = this.x + otherVector.x;
  1662. result.y = this.y + otherVector.y;
  1663. return this;
  1664. };
  1665. /**
  1666. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1667. * Returns the updated Vector2.
  1668. */
  1669. Vector2.prototype.addInPlace = function (otherVector) {
  1670. this.x += otherVector.x;
  1671. this.y += otherVector.y;
  1672. return this;
  1673. };
  1674. /**
  1675. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1676. */
  1677. Vector2.prototype.addVector3 = function (otherVector) {
  1678. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1679. };
  1680. /**
  1681. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1682. */
  1683. Vector2.prototype.subtract = function (otherVector) {
  1684. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1685. };
  1686. /**
  1687. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1688. * Returns the Vector2.
  1689. */
  1690. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1691. result.x = this.x - otherVector.x;
  1692. result.y = this.y - otherVector.y;
  1693. return this;
  1694. };
  1695. /**
  1696. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1697. * Returns the updated Vector2.
  1698. */
  1699. Vector2.prototype.subtractInPlace = function (otherVector) {
  1700. this.x -= otherVector.x;
  1701. this.y -= otherVector.y;
  1702. return this;
  1703. };
  1704. /**
  1705. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1706. * Returns the updated Vector2.
  1707. */
  1708. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1709. this.x *= otherVector.x;
  1710. this.y *= otherVector.y;
  1711. return this;
  1712. };
  1713. /**
  1714. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1715. */
  1716. Vector2.prototype.multiply = function (otherVector) {
  1717. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1718. };
  1719. /**
  1720. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1721. * Returns the Vector2.
  1722. */
  1723. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1724. result.x = this.x * otherVector.x;
  1725. result.y = this.y * otherVector.y;
  1726. return this;
  1727. };
  1728. /**
  1729. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1730. */
  1731. Vector2.prototype.multiplyByFloats = function (x, y) {
  1732. return new Vector2(this.x * x, this.y * y);
  1733. };
  1734. /**
  1735. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1736. */
  1737. Vector2.prototype.divide = function (otherVector) {
  1738. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1739. };
  1740. /**
  1741. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1742. * Returns the Vector2.
  1743. */
  1744. Vector2.prototype.divideToRef = function (otherVector, result) {
  1745. result.x = this.x / otherVector.x;
  1746. result.y = this.y / otherVector.y;
  1747. return this;
  1748. };
  1749. /**
  1750. * Divides the current Vector3 coordinates by the passed ones.
  1751. * Returns the updated Vector3.
  1752. */
  1753. Vector2.prototype.divideInPlace = function (otherVector) {
  1754. return this.divideToRef(otherVector, this);
  1755. };
  1756. /**
  1757. * Returns a new Vector2 with current Vector2 negated coordinates.
  1758. */
  1759. Vector2.prototype.negate = function () {
  1760. return new Vector2(-this.x, -this.y);
  1761. };
  1762. /**
  1763. * Multiply the Vector2 coordinates by scale.
  1764. * Returns the updated Vector2.
  1765. */
  1766. Vector2.prototype.scaleInPlace = function (scale) {
  1767. this.x *= scale;
  1768. this.y *= scale;
  1769. return this;
  1770. };
  1771. /**
  1772. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1773. */
  1774. Vector2.prototype.scale = function (scale) {
  1775. return new Vector2(this.x * scale, this.y * scale);
  1776. };
  1777. /**
  1778. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1779. */
  1780. Vector2.prototype.equals = function (otherVector) {
  1781. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1782. };
  1783. /**
  1784. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1785. */
  1786. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1787. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1788. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1789. };
  1790. // Properties
  1791. /**
  1792. * Returns the vector length (float).
  1793. */
  1794. Vector2.prototype.length = function () {
  1795. return Math.sqrt(this.x * this.x + this.y * this.y);
  1796. };
  1797. /**
  1798. * Returns the vector squared length (float);
  1799. */
  1800. Vector2.prototype.lengthSquared = function () {
  1801. return (this.x * this.x + this.y * this.y);
  1802. };
  1803. // Methods
  1804. /**
  1805. * Normalize the vector.
  1806. * Returns the updated Vector2.
  1807. */
  1808. Vector2.prototype.normalize = function () {
  1809. var len = this.length();
  1810. if (len === 0)
  1811. return this;
  1812. var num = 1.0 / len;
  1813. this.x *= num;
  1814. this.y *= num;
  1815. return this;
  1816. };
  1817. /**
  1818. * Returns a new Vector2 copied from the Vector2.
  1819. */
  1820. Vector2.prototype.clone = function () {
  1821. return new Vector2(this.x, this.y);
  1822. };
  1823. // Statics
  1824. /**
  1825. * Returns a new Vector2(0, 0)
  1826. */
  1827. Vector2.Zero = function () {
  1828. return new Vector2(0, 0);
  1829. };
  1830. /**
  1831. * Returns a new Vector2(1, 1)
  1832. */
  1833. Vector2.One = function () {
  1834. return new Vector2(1, 1);
  1835. };
  1836. /**
  1837. * Returns a new Vector2 set from the passed index element of the passed array.
  1838. */
  1839. Vector2.FromArray = function (array, offset) {
  1840. if (offset === void 0) { offset = 0; }
  1841. return new Vector2(array[offset], array[offset + 1]);
  1842. };
  1843. /**
  1844. * Sets "result" from the passed index element of the passed array.
  1845. */
  1846. Vector2.FromArrayToRef = function (array, offset, result) {
  1847. result.x = array[offset];
  1848. result.y = array[offset + 1];
  1849. };
  1850. /**
  1851. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1852. */
  1853. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1854. var squared = amount * amount;
  1855. var cubed = amount * squared;
  1856. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1857. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1858. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1859. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1860. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1861. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1862. return new Vector2(x, y);
  1863. };
  1864. /**
  1865. * 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".
  1866. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1867. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1868. */
  1869. Vector2.Clamp = function (value, min, max) {
  1870. var x = value.x;
  1871. x = (x > max.x) ? max.x : x;
  1872. x = (x < min.x) ? min.x : x;
  1873. var y = value.y;
  1874. y = (y > max.y) ? max.y : y;
  1875. y = (y < min.y) ? min.y : y;
  1876. return new Vector2(x, y);
  1877. };
  1878. /**
  1879. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1880. */
  1881. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1882. var squared = amount * amount;
  1883. var cubed = amount * squared;
  1884. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1885. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1886. var part3 = (cubed - (2.0 * squared)) + amount;
  1887. var part4 = cubed - squared;
  1888. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1889. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1890. return new Vector2(x, y);
  1891. };
  1892. /**
  1893. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1894. */
  1895. Vector2.Lerp = function (start, end, amount) {
  1896. var x = start.x + ((end.x - start.x) * amount);
  1897. var y = start.y + ((end.y - start.y) * amount);
  1898. return new Vector2(x, y);
  1899. };
  1900. /**
  1901. * Returns the dot product (float) of the vector "left" and the vector "right".
  1902. */
  1903. Vector2.Dot = function (left, right) {
  1904. return left.x * right.x + left.y * right.y;
  1905. };
  1906. /**
  1907. * Returns a new Vector2 equal to the normalized passed vector.
  1908. */
  1909. Vector2.Normalize = function (vector) {
  1910. var newVector = vector.clone();
  1911. newVector.normalize();
  1912. return newVector;
  1913. };
  1914. /**
  1915. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1916. */
  1917. Vector2.Minimize = function (left, right) {
  1918. var x = (left.x < right.x) ? left.x : right.x;
  1919. var y = (left.y < right.y) ? left.y : right.y;
  1920. return new Vector2(x, y);
  1921. };
  1922. /**
  1923. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1924. */
  1925. Vector2.Maximize = function (left, right) {
  1926. var x = (left.x > right.x) ? left.x : right.x;
  1927. var y = (left.y > right.y) ? left.y : right.y;
  1928. return new Vector2(x, y);
  1929. };
  1930. /**
  1931. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1932. */
  1933. Vector2.Transform = function (vector, transformation) {
  1934. var r = Vector2.Zero();
  1935. Vector2.TransformToRef(vector, transformation, r);
  1936. return r;
  1937. };
  1938. /**
  1939. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1940. */
  1941. Vector2.TransformToRef = function (vector, transformation, result) {
  1942. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1943. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1944. result.x = x;
  1945. result.y = y;
  1946. };
  1947. /**
  1948. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1949. */
  1950. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1951. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1952. var sign = a < 0 ? -1 : 1;
  1953. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1954. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1955. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1956. };
  1957. /**
  1958. * Returns the distance (float) between the vectors "value1" and "value2".
  1959. */
  1960. Vector2.Distance = function (value1, value2) {
  1961. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1962. };
  1963. /**
  1964. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1965. */
  1966. Vector2.DistanceSquared = function (value1, value2) {
  1967. var x = value1.x - value2.x;
  1968. var y = value1.y - value2.y;
  1969. return (x * x) + (y * y);
  1970. };
  1971. /**
  1972. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1973. */
  1974. Vector2.Center = function (value1, value2) {
  1975. var center = value1.add(value2);
  1976. center.scaleInPlace(0.5);
  1977. return center;
  1978. };
  1979. /**
  1980. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1981. */
  1982. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1983. var l2 = Vector2.DistanceSquared(segA, segB);
  1984. if (l2 === 0.0) {
  1985. return Vector2.Distance(p, segA);
  1986. }
  1987. var v = segB.subtract(segA);
  1988. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1989. var proj = segA.add(v.multiplyByFloats(t, t));
  1990. return Vector2.Distance(p, proj);
  1991. };
  1992. return Vector2;
  1993. }());
  1994. BABYLON.Vector2 = Vector2;
  1995. var Vector3 = /** @class */ (function () {
  1996. /**
  1997. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1998. * A Vector3 is the main object used in 3D geometry.
  1999. * It can represent etiher the coordinates of a point the space, either a direction.
  2000. */
  2001. function Vector3(x, y, z) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. }
  2006. /**
  2007. * Returns a string with the Vector3 coordinates.
  2008. */
  2009. Vector3.prototype.toString = function () {
  2010. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2011. };
  2012. /**
  2013. * Returns the string "Vector3"
  2014. */
  2015. Vector3.prototype.getClassName = function () {
  2016. return "Vector3";
  2017. };
  2018. /**
  2019. * Returns the Vector hash code.
  2020. */
  2021. Vector3.prototype.getHashCode = function () {
  2022. var hash = this.x || 0;
  2023. hash = (hash * 397) ^ (this.y || 0);
  2024. hash = (hash * 397) ^ (this.z || 0);
  2025. return hash;
  2026. };
  2027. // Operators
  2028. /**
  2029. * Returns a new array with three elements : the coordinates the Vector3.
  2030. */
  2031. Vector3.prototype.asArray = function () {
  2032. var result = [];
  2033. this.toArray(result, 0);
  2034. return result;
  2035. };
  2036. /**
  2037. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2038. * Returns the Vector3.
  2039. */
  2040. Vector3.prototype.toArray = function (array, index) {
  2041. if (index === void 0) { index = 0; }
  2042. array[index] = this.x;
  2043. array[index + 1] = this.y;
  2044. array[index + 2] = this.z;
  2045. return this;
  2046. };
  2047. /**
  2048. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2049. */
  2050. Vector3.prototype.toQuaternion = function () {
  2051. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2052. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2053. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2054. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2055. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2056. var cosy = Math.cos(this.y * 0.5);
  2057. var siny = Math.sin(this.y * 0.5);
  2058. result.x = coszMinusx * siny;
  2059. result.y = -sinzMinusx * siny;
  2060. result.z = sinxPlusz * cosy;
  2061. result.w = cosxPlusz * cosy;
  2062. return result;
  2063. };
  2064. /**
  2065. * Adds the passed vector to the current Vector3.
  2066. * Returns the updated Vector3.
  2067. */
  2068. Vector3.prototype.addInPlace = function (otherVector) {
  2069. this.x += otherVector.x;
  2070. this.y += otherVector.y;
  2071. this.z += otherVector.z;
  2072. return this;
  2073. };
  2074. /**
  2075. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2076. */
  2077. Vector3.prototype.add = function (otherVector) {
  2078. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2079. };
  2080. /**
  2081. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2082. * Returns the current Vector3.
  2083. */
  2084. Vector3.prototype.addToRef = function (otherVector, result) {
  2085. result.x = this.x + otherVector.x;
  2086. result.y = this.y + otherVector.y;
  2087. result.z = this.z + otherVector.z;
  2088. return this;
  2089. };
  2090. /**
  2091. * Subtract the passed vector from the current Vector3.
  2092. * Returns the updated Vector3.
  2093. */
  2094. Vector3.prototype.subtractInPlace = function (otherVector) {
  2095. this.x -= otherVector.x;
  2096. this.y -= otherVector.y;
  2097. this.z -= otherVector.z;
  2098. return this;
  2099. };
  2100. /**
  2101. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2102. */
  2103. Vector3.prototype.subtract = function (otherVector) {
  2104. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2105. };
  2106. /**
  2107. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2108. * Returns the current Vector3.
  2109. */
  2110. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2111. result.x = this.x - otherVector.x;
  2112. result.y = this.y - otherVector.y;
  2113. result.z = this.z - otherVector.z;
  2114. return this;
  2115. };
  2116. /**
  2117. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2118. */
  2119. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2120. return new Vector3(this.x - x, this.y - y, this.z - z);
  2121. };
  2122. /**
  2123. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2124. * Returns the current Vector3.
  2125. */
  2126. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2127. result.x = this.x - x;
  2128. result.y = this.y - y;
  2129. result.z = this.z - z;
  2130. return this;
  2131. };
  2132. /**
  2133. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2134. */
  2135. Vector3.prototype.negate = function () {
  2136. return new Vector3(-this.x, -this.y, -this.z);
  2137. };
  2138. /**
  2139. * Multiplies the Vector3 coordinates by the float "scale".
  2140. * Returns the updated Vector3.
  2141. */
  2142. Vector3.prototype.scaleInPlace = function (scale) {
  2143. this.x *= scale;
  2144. this.y *= scale;
  2145. this.z *= scale;
  2146. return this;
  2147. };
  2148. /**
  2149. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2150. */
  2151. Vector3.prototype.scale = function (scale) {
  2152. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2153. };
  2154. /**
  2155. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2156. * Returns the current Vector3.
  2157. */
  2158. Vector3.prototype.scaleToRef = function (scale, result) {
  2159. result.x = this.x * scale;
  2160. result.y = this.y * scale;
  2161. result.z = this.z * scale;
  2162. return this;
  2163. };
  2164. /**
  2165. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2166. */
  2167. Vector3.prototype.equals = function (otherVector) {
  2168. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2169. };
  2170. /**
  2171. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2172. */
  2173. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2174. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2175. 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);
  2176. };
  2177. /**
  2178. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2179. */
  2180. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2181. return this.x === x && this.y === y && this.z === z;
  2182. };
  2183. /**
  2184. * Muliplies the current Vector3 coordinates by the passed ones.
  2185. * Returns the updated Vector3.
  2186. */
  2187. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2188. this.x *= otherVector.x;
  2189. this.y *= otherVector.y;
  2190. this.z *= otherVector.z;
  2191. return this;
  2192. };
  2193. /**
  2194. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2195. */
  2196. Vector3.prototype.multiply = function (otherVector) {
  2197. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2198. };
  2199. /**
  2200. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2201. * Returns the current Vector3.
  2202. */
  2203. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2204. result.x = this.x * otherVector.x;
  2205. result.y = this.y * otherVector.y;
  2206. result.z = this.z * otherVector.z;
  2207. return this;
  2208. };
  2209. /**
  2210. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2211. */
  2212. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2213. return new Vector3(this.x * x, this.y * y, this.z * z);
  2214. };
  2215. /**
  2216. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2217. */
  2218. Vector3.prototype.divide = function (otherVector) {
  2219. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2220. };
  2221. /**
  2222. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2223. * Returns the current Vector3.
  2224. */
  2225. Vector3.prototype.divideToRef = function (otherVector, result) {
  2226. result.x = this.x / otherVector.x;
  2227. result.y = this.y / otherVector.y;
  2228. result.z = this.z / otherVector.z;
  2229. return this;
  2230. };
  2231. /**
  2232. * Divides the current Vector3 coordinates by the passed ones.
  2233. * Returns the updated Vector3.
  2234. */
  2235. Vector3.prototype.divideInPlace = function (otherVector) {
  2236. return this.divideToRef(otherVector, this);
  2237. };
  2238. /**
  2239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2240. * Returns the updated Vector3.
  2241. */
  2242. Vector3.prototype.MinimizeInPlace = function (other) {
  2243. if (other.x < this.x)
  2244. this.x = other.x;
  2245. if (other.y < this.y)
  2246. this.y = other.y;
  2247. if (other.z < this.z)
  2248. this.z = other.z;
  2249. return this;
  2250. };
  2251. /**
  2252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2253. * Returns the updated Vector3.
  2254. */
  2255. Vector3.prototype.MaximizeInPlace = function (other) {
  2256. if (other.x > this.x)
  2257. this.x = other.x;
  2258. if (other.y > this.y)
  2259. this.y = other.y;
  2260. if (other.z > this.z)
  2261. this.z = other.z;
  2262. return this;
  2263. };
  2264. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2265. /**
  2266. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2267. */
  2268. get: function () {
  2269. var absX = Math.abs(this.x);
  2270. var absY = Math.abs(this.y);
  2271. if (absX !== absY) {
  2272. return true;
  2273. }
  2274. var absZ = Math.abs(this.z);
  2275. if (absX !== absZ) {
  2276. return true;
  2277. }
  2278. if (absY !== absZ) {
  2279. return true;
  2280. }
  2281. return false;
  2282. },
  2283. enumerable: true,
  2284. configurable: true
  2285. });
  2286. // Properties
  2287. /**
  2288. * Returns the length of the Vector3 (float).
  2289. */
  2290. Vector3.prototype.length = function () {
  2291. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2292. };
  2293. /**
  2294. * Returns the squared length of the Vector3 (float).
  2295. */
  2296. Vector3.prototype.lengthSquared = function () {
  2297. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2298. };
  2299. /**
  2300. * Normalize the current Vector3.
  2301. * Returns the updated Vector3.
  2302. * /!\ In place operation.
  2303. */
  2304. Vector3.prototype.normalize = function () {
  2305. var len = this.length();
  2306. if (len === 0 || len === 1.0)
  2307. return this;
  2308. var num = 1.0 / len;
  2309. this.x *= num;
  2310. this.y *= num;
  2311. this.z *= num;
  2312. return this;
  2313. };
  2314. /**
  2315. * Normalize the current Vector3 to a new vector.
  2316. * @returns the new Vector3.
  2317. */
  2318. Vector3.prototype.normalizeToNew = function () {
  2319. var normalized = new Vector3(0, 0, 0);
  2320. this.normalizeToRef(normalized);
  2321. return normalized;
  2322. };
  2323. /**
  2324. * Normalize the current Vector3 to the reference.
  2325. * @param the reference to update.
  2326. * @returns the updated Vector3.
  2327. */
  2328. Vector3.prototype.normalizeToRef = function (reference) {
  2329. var len = this.length();
  2330. if (len === 0 || len === 1.0) {
  2331. reference.set(this.x, this.y, this.z);
  2332. return reference;
  2333. }
  2334. var scale = 1.0 / len;
  2335. this.scaleToRef(scale, reference);
  2336. return reference;
  2337. };
  2338. /**
  2339. * Returns a new Vector3 copied from the current Vector3.
  2340. */
  2341. Vector3.prototype.clone = function () {
  2342. return new Vector3(this.x, this.y, this.z);
  2343. };
  2344. /**
  2345. * Copies the passed vector coordinates to the current Vector3 ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector3.prototype.copyFrom = function (source) {
  2349. this.x = source.x;
  2350. this.y = source.y;
  2351. this.z = source.z;
  2352. return this;
  2353. };
  2354. /**
  2355. * Copies the passed floats to the current Vector3 coordinates.
  2356. * Returns the updated Vector3.
  2357. */
  2358. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2359. this.x = x;
  2360. this.y = y;
  2361. this.z = z;
  2362. return this;
  2363. };
  2364. /**
  2365. * Copies the passed floats to the current Vector3 coordinates.
  2366. * Returns the updated Vector3.
  2367. */
  2368. Vector3.prototype.set = function (x, y, z) {
  2369. return this.copyFromFloats(x, y, z);
  2370. };
  2371. // Statics
  2372. /**
  2373. *
  2374. */
  2375. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2376. var d0 = Vector3.Dot(vector0, axis) - size;
  2377. var d1 = Vector3.Dot(vector1, axis) - size;
  2378. var s = d0 / (d0 - d1);
  2379. return s;
  2380. };
  2381. /**
  2382. * Get angle between two vectors.
  2383. * @param vector0 angle between vector0 and vector1
  2384. * @param vector1 angle between vector0 and vector1
  2385. * @param normal direction of the normal.
  2386. * @return the angle between vector0 and vector1.
  2387. */
  2388. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2389. var v0 = vector0.clone().normalize();
  2390. var v1 = vector1.clone().normalize();
  2391. var dot = Vector3.Dot(v0, v1);
  2392. var n = Vector3.Cross(v0, v1);
  2393. if (Vector3.Dot(n, normal) > 0) {
  2394. return Math.acos(dot);
  2395. }
  2396. return -Math.acos(dot);
  2397. };
  2398. /**
  2399. * Returns a new Vector3 set from the index "offset" of the passed array.
  2400. */
  2401. Vector3.FromArray = function (array, offset) {
  2402. if (!offset) {
  2403. offset = 0;
  2404. }
  2405. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2406. };
  2407. /**
  2408. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2409. * This function is deprecated. Use FromArray instead.
  2410. */
  2411. Vector3.FromFloatArray = function (array, offset) {
  2412. return Vector3.FromArray(array, offset);
  2413. };
  2414. /**
  2415. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2416. */
  2417. Vector3.FromArrayToRef = function (array, offset, result) {
  2418. result.x = array[offset];
  2419. result.y = array[offset + 1];
  2420. result.z = array[offset + 2];
  2421. };
  2422. /**
  2423. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2424. * This function is deprecated. Use FromArrayToRef instead.
  2425. */
  2426. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2427. return Vector3.FromArrayToRef(array, offset, result);
  2428. };
  2429. /**
  2430. * Sets the passed vector "result" with the passed floats.
  2431. */
  2432. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2433. result.x = x;
  2434. result.y = y;
  2435. result.z = z;
  2436. };
  2437. /**
  2438. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2439. */
  2440. Vector3.Zero = function () {
  2441. return new Vector3(0.0, 0.0, 0.0);
  2442. };
  2443. /**
  2444. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2445. */
  2446. Vector3.One = function () {
  2447. return new Vector3(1.0, 1.0, 1.0);
  2448. };
  2449. /**
  2450. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2451. */
  2452. Vector3.Up = function () {
  2453. return new Vector3(0.0, 1.0, 0.0);
  2454. };
  2455. /**
  2456. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2457. */
  2458. Vector3.Forward = function () {
  2459. return new Vector3(0.0, 0.0, 1.0);
  2460. };
  2461. /**
  2462. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2463. */
  2464. Vector3.Right = function () {
  2465. return new Vector3(1.0, 0.0, 0.0);
  2466. };
  2467. /**
  2468. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2469. */
  2470. Vector3.Left = function () {
  2471. return new Vector3(-1.0, 0.0, 0.0);
  2472. };
  2473. /**
  2474. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2475. * This method computes tranformed coordinates only, not transformed direction vectors.
  2476. */
  2477. Vector3.TransformCoordinates = function (vector, transformation) {
  2478. var result = Vector3.Zero();
  2479. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2480. return result;
  2481. };
  2482. /**
  2483. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2484. * This method computes tranformed coordinates only, not transformed direction vectors.
  2485. */
  2486. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2487. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2488. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2489. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2490. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2491. result.x = x / w;
  2492. result.y = y / w;
  2493. result.z = z / w;
  2494. };
  2495. /**
  2496. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2497. * This method computes tranformed coordinates only, not transformed direction vectors.
  2498. */
  2499. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2500. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2501. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2502. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2503. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2504. result.x = rx / rw;
  2505. result.y = ry / rw;
  2506. result.z = rz / rw;
  2507. };
  2508. /**
  2509. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2510. * This methods computes transformed normalized direction vectors only.
  2511. */
  2512. Vector3.TransformNormal = function (vector, transformation) {
  2513. var result = Vector3.Zero();
  2514. Vector3.TransformNormalToRef(vector, transformation, result);
  2515. return result;
  2516. };
  2517. /**
  2518. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2519. * This methods computes transformed normalized direction vectors only.
  2520. */
  2521. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2522. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2523. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2524. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2525. result.x = x;
  2526. result.y = y;
  2527. result.z = z;
  2528. };
  2529. /**
  2530. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2531. * This methods computes transformed normalized direction vectors only.
  2532. */
  2533. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2534. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2535. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2536. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2537. };
  2538. /**
  2539. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2540. */
  2541. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2551. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2552. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2553. return new Vector3(x, y, z);
  2554. };
  2555. /**
  2556. * 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".
  2557. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2558. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2559. */
  2560. Vector3.Clamp = function (value, min, max) {
  2561. var x = value.x;
  2562. x = (x > max.x) ? max.x : x;
  2563. x = (x < min.x) ? min.x : x;
  2564. var y = value.y;
  2565. y = (y > max.y) ? max.y : y;
  2566. y = (y < min.y) ? min.y : y;
  2567. var z = value.z;
  2568. z = (z > max.z) ? max.z : z;
  2569. z = (z < min.z) ? min.z : z;
  2570. return new Vector3(x, y, z);
  2571. };
  2572. /**
  2573. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2574. */
  2575. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2576. var squared = amount * amount;
  2577. var cubed = amount * squared;
  2578. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2579. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2580. var part3 = (cubed - (2.0 * squared)) + amount;
  2581. var part4 = cubed - squared;
  2582. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2583. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2584. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2585. return new Vector3(x, y, z);
  2586. };
  2587. /**
  2588. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2589. */
  2590. Vector3.Lerp = function (start, end, amount) {
  2591. var result = new Vector3(0, 0, 0);
  2592. Vector3.LerpToRef(start, end, amount, result);
  2593. return result;
  2594. };
  2595. /**
  2596. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2597. */
  2598. Vector3.LerpToRef = function (start, end, amount, result) {
  2599. result.x = start.x + ((end.x - start.x) * amount);
  2600. result.y = start.y + ((end.y - start.y) * amount);
  2601. result.z = start.z + ((end.z - start.z) * amount);
  2602. };
  2603. /**
  2604. * Returns the dot product (float) between the vectors "left" and "right".
  2605. */
  2606. Vector3.Dot = function (left, right) {
  2607. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2608. };
  2609. /**
  2610. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2611. * The cross product is then orthogonal to both "left" and "right".
  2612. */
  2613. Vector3.Cross = function (left, right) {
  2614. var result = Vector3.Zero();
  2615. Vector3.CrossToRef(left, right, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed vector "result" with the cross product of "left" and "right".
  2620. * The cross product is then orthogonal to both "left" and "right".
  2621. */
  2622. Vector3.CrossToRef = function (left, right, result) {
  2623. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2624. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2625. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2626. result.copyFrom(MathTmp.Vector3[0]);
  2627. };
  2628. /**
  2629. * Returns a new Vector3 as the normalization of the passed vector.
  2630. */
  2631. Vector3.Normalize = function (vector) {
  2632. var result = Vector3.Zero();
  2633. Vector3.NormalizeToRef(vector, result);
  2634. return result;
  2635. };
  2636. /**
  2637. * Sets the passed vector "result" with the normalization of the passed first vector.
  2638. */
  2639. Vector3.NormalizeToRef = function (vector, result) {
  2640. result.copyFrom(vector);
  2641. result.normalize();
  2642. };
  2643. Vector3.Project = function (vector, world, transform, viewport) {
  2644. var cw = viewport.width;
  2645. var ch = viewport.height;
  2646. var cx = viewport.x;
  2647. var cy = viewport.y;
  2648. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2649. 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);
  2650. var matrix = MathTmp.Matrix[0];
  2651. world.multiplyToRef(transform, matrix);
  2652. matrix.multiplyToRef(viewportMatrix, matrix);
  2653. return Vector3.TransformCoordinates(vector, matrix);
  2654. };
  2655. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2656. var matrix = MathTmp.Matrix[0];
  2657. world.multiplyToRef(transform, matrix);
  2658. matrix.invert();
  2659. source.x = source.x / viewportWidth * 2 - 1;
  2660. source.y = -(source.y / viewportHeight * 2 - 1);
  2661. var vector = Vector3.TransformCoordinates(source, matrix);
  2662. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2663. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2664. vector = vector.scale(1.0 / num);
  2665. }
  2666. return vector;
  2667. };
  2668. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2669. var result = Vector3.Zero();
  2670. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2671. return result;
  2672. };
  2673. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2674. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2675. };
  2676. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2677. var matrix = MathTmp.Matrix[0];
  2678. world.multiplyToRef(view, matrix);
  2679. matrix.multiplyToRef(projection, matrix);
  2680. matrix.invert();
  2681. var screenSource = MathTmp.Vector3[0];
  2682. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2683. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2684. screenSource.z = 2 * sourceZ - 1.0;
  2685. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2686. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2687. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2688. result.scaleInPlace(1.0 / num);
  2689. }
  2690. };
  2691. Vector3.Minimize = function (left, right) {
  2692. var min = left.clone();
  2693. min.MinimizeInPlace(right);
  2694. return min;
  2695. };
  2696. Vector3.Maximize = function (left, right) {
  2697. var max = left.clone();
  2698. max.MaximizeInPlace(right);
  2699. return max;
  2700. };
  2701. /**
  2702. * Returns the distance (float) between the vectors "value1" and "value2".
  2703. */
  2704. Vector3.Distance = function (value1, value2) {
  2705. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2706. };
  2707. /**
  2708. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2709. */
  2710. Vector3.DistanceSquared = function (value1, value2) {
  2711. var x = value1.x - value2.x;
  2712. var y = value1.y - value2.y;
  2713. var z = value1.z - value2.z;
  2714. return (x * x) + (y * y) + (z * z);
  2715. };
  2716. /**
  2717. * Returns a new Vector3 located at the center between "value1" and "value2".
  2718. */
  2719. Vector3.Center = function (value1, value2) {
  2720. var center = value1.add(value2);
  2721. center.scaleInPlace(0.5);
  2722. return center;
  2723. };
  2724. /**
  2725. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2726. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2727. * to something in order to rotate it from its local system to the given target system.
  2728. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2729. * Returns a new Vector3.
  2730. */
  2731. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2732. var rotation = Vector3.Zero();
  2733. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2734. return rotation;
  2735. };
  2736. /**
  2737. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2738. */
  2739. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2740. var quat = MathTmp.Quaternion[0];
  2741. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2742. quat.toEulerAnglesToRef(ref);
  2743. };
  2744. return Vector3;
  2745. }());
  2746. BABYLON.Vector3 = Vector3;
  2747. //Vector4 class created for EulerAngle class conversion to Quaternion
  2748. var Vector4 = /** @class */ (function () {
  2749. /**
  2750. * Creates a Vector4 object from the passed floats.
  2751. */
  2752. function Vector4(x, y, z, w) {
  2753. this.x = x;
  2754. this.y = y;
  2755. this.z = z;
  2756. this.w = w;
  2757. }
  2758. /**
  2759. * Returns the string with the Vector4 coordinates.
  2760. */
  2761. Vector4.prototype.toString = function () {
  2762. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2763. };
  2764. /**
  2765. * Returns the string "Vector4".
  2766. */
  2767. Vector4.prototype.getClassName = function () {
  2768. return "Vector4";
  2769. };
  2770. /**
  2771. * Returns the Vector4 hash code.
  2772. */
  2773. Vector4.prototype.getHashCode = function () {
  2774. var hash = this.x || 0;
  2775. hash = (hash * 397) ^ (this.y || 0);
  2776. hash = (hash * 397) ^ (this.z || 0);
  2777. hash = (hash * 397) ^ (this.w || 0);
  2778. return hash;
  2779. };
  2780. // Operators
  2781. /**
  2782. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2783. */
  2784. Vector4.prototype.asArray = function () {
  2785. var result = new Array();
  2786. this.toArray(result, 0);
  2787. return result;
  2788. };
  2789. /**
  2790. * Populates the passed array from the passed index with the Vector4 coordinates.
  2791. * Returns the Vector4.
  2792. */
  2793. Vector4.prototype.toArray = function (array, index) {
  2794. if (index === undefined) {
  2795. index = 0;
  2796. }
  2797. array[index] = this.x;
  2798. array[index + 1] = this.y;
  2799. array[index + 2] = this.z;
  2800. array[index + 3] = this.w;
  2801. return this;
  2802. };
  2803. /**
  2804. * Adds the passed vector to the current Vector4.
  2805. * Returns the updated Vector4.
  2806. */
  2807. Vector4.prototype.addInPlace = function (otherVector) {
  2808. this.x += otherVector.x;
  2809. this.y += otherVector.y;
  2810. this.z += otherVector.z;
  2811. this.w += otherVector.w;
  2812. return this;
  2813. };
  2814. /**
  2815. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2816. */
  2817. Vector4.prototype.add = function (otherVector) {
  2818. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2819. };
  2820. /**
  2821. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2822. * Returns the current Vector4.
  2823. */
  2824. Vector4.prototype.addToRef = function (otherVector, result) {
  2825. result.x = this.x + otherVector.x;
  2826. result.y = this.y + otherVector.y;
  2827. result.z = this.z + otherVector.z;
  2828. result.w = this.w + otherVector.w;
  2829. return this;
  2830. };
  2831. /**
  2832. * Subtract in place the passed vector from the current Vector4.
  2833. * Returns the updated Vector4.
  2834. */
  2835. Vector4.prototype.subtractInPlace = function (otherVector) {
  2836. this.x -= otherVector.x;
  2837. this.y -= otherVector.y;
  2838. this.z -= otherVector.z;
  2839. this.w -= otherVector.w;
  2840. return this;
  2841. };
  2842. /**
  2843. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2844. */
  2845. Vector4.prototype.subtract = function (otherVector) {
  2846. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2847. };
  2848. /**
  2849. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2850. * Returns the current Vector4.
  2851. */
  2852. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2853. result.x = this.x - otherVector.x;
  2854. result.y = this.y - otherVector.y;
  2855. result.z = this.z - otherVector.z;
  2856. result.w = this.w - otherVector.w;
  2857. return this;
  2858. };
  2859. /**
  2860. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2861. */
  2862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2864. };
  2865. /**
  2866. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2867. * Returns the current Vector4.
  2868. */
  2869. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2870. result.x = this.x - x;
  2871. result.y = this.y - y;
  2872. result.z = this.z - z;
  2873. result.w = this.w - w;
  2874. return this;
  2875. };
  2876. /**
  2877. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2878. */
  2879. Vector4.prototype.negate = function () {
  2880. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2881. };
  2882. /**
  2883. * Multiplies the current Vector4 coordinates by scale (float).
  2884. * Returns the updated Vector4.
  2885. */
  2886. Vector4.prototype.scaleInPlace = function (scale) {
  2887. this.x *= scale;
  2888. this.y *= scale;
  2889. this.z *= scale;
  2890. this.w *= scale;
  2891. return this;
  2892. };
  2893. /**
  2894. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2895. */
  2896. Vector4.prototype.scale = function (scale) {
  2897. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2898. };
  2899. /**
  2900. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2901. * Returns the current Vector4.
  2902. */
  2903. Vector4.prototype.scaleToRef = function (scale, result) {
  2904. result.x = this.x * scale;
  2905. result.y = this.y * scale;
  2906. result.z = this.z * scale;
  2907. result.w = this.w * scale;
  2908. return this;
  2909. };
  2910. /**
  2911. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2912. */
  2913. Vector4.prototype.equals = function (otherVector) {
  2914. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2915. };
  2916. /**
  2917. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2918. */
  2919. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2920. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2921. return otherVector
  2922. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2923. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2924. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2925. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2926. };
  2927. /**
  2928. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2929. */
  2930. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2931. return this.x === x && this.y === y && this.z === z && this.w === w;
  2932. };
  2933. /**
  2934. * Multiplies in place the current Vector4 by the passed one.
  2935. * Returns the updated Vector4.
  2936. */
  2937. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2938. this.x *= otherVector.x;
  2939. this.y *= otherVector.y;
  2940. this.z *= otherVector.z;
  2941. this.w *= otherVector.w;
  2942. return this;
  2943. };
  2944. /**
  2945. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2946. */
  2947. Vector4.prototype.multiply = function (otherVector) {
  2948. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2949. };
  2950. /**
  2951. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2952. * Returns the current Vector4.
  2953. */
  2954. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2955. result.x = this.x * otherVector.x;
  2956. result.y = this.y * otherVector.y;
  2957. result.z = this.z * otherVector.z;
  2958. result.w = this.w * otherVector.w;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2963. */
  2964. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2965. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2966. };
  2967. /**
  2968. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2969. */
  2970. Vector4.prototype.divide = function (otherVector) {
  2971. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2972. };
  2973. /**
  2974. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2975. * Returns the current Vector4.
  2976. */
  2977. Vector4.prototype.divideToRef = function (otherVector, result) {
  2978. result.x = this.x / otherVector.x;
  2979. result.y = this.y / otherVector.y;
  2980. result.z = this.z / otherVector.z;
  2981. result.w = this.w / otherVector.w;
  2982. return this;
  2983. };
  2984. /**
  2985. * Divides the current Vector3 coordinates by the passed ones.
  2986. * Returns the updated Vector3.
  2987. */
  2988. Vector4.prototype.divideInPlace = function (otherVector) {
  2989. return this.divideToRef(otherVector, this);
  2990. };
  2991. /**
  2992. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2993. */
  2994. Vector4.prototype.MinimizeInPlace = function (other) {
  2995. if (other.x < this.x)
  2996. this.x = other.x;
  2997. if (other.y < this.y)
  2998. this.y = other.y;
  2999. if (other.z < this.z)
  3000. this.z = other.z;
  3001. if (other.w < this.w)
  3002. this.w = other.w;
  3003. return this;
  3004. };
  3005. /**
  3006. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3007. */
  3008. Vector4.prototype.MaximizeInPlace = function (other) {
  3009. if (other.x > this.x)
  3010. this.x = other.x;
  3011. if (other.y > this.y)
  3012. this.y = other.y;
  3013. if (other.z > this.z)
  3014. this.z = other.z;
  3015. if (other.w > this.w)
  3016. this.w = other.w;
  3017. return this;
  3018. };
  3019. // Properties
  3020. /**
  3021. * Returns the Vector4 length (float).
  3022. */
  3023. Vector4.prototype.length = function () {
  3024. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3025. };
  3026. /**
  3027. * Returns the Vector4 squared length (float).
  3028. */
  3029. Vector4.prototype.lengthSquared = function () {
  3030. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3031. };
  3032. // Methods
  3033. /**
  3034. * Normalizes in place the Vector4.
  3035. * Returns the updated Vector4.
  3036. */
  3037. Vector4.prototype.normalize = function () {
  3038. var len = this.length();
  3039. if (len === 0)
  3040. return this;
  3041. var num = 1.0 / len;
  3042. this.x *= num;
  3043. this.y *= num;
  3044. this.z *= num;
  3045. this.w *= num;
  3046. return this;
  3047. };
  3048. /**
  3049. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3050. */
  3051. Vector4.prototype.toVector3 = function () {
  3052. return new Vector3(this.x, this.y, this.z);
  3053. };
  3054. /**
  3055. * Returns a new Vector4 copied from the current one.
  3056. */
  3057. Vector4.prototype.clone = function () {
  3058. return new Vector4(this.x, this.y, this.z, this.w);
  3059. };
  3060. /**
  3061. * Updates the current Vector4 with the passed one coordinates.
  3062. * Returns the updated Vector4.
  3063. */
  3064. Vector4.prototype.copyFrom = function (source) {
  3065. this.x = source.x;
  3066. this.y = source.y;
  3067. this.z = source.z;
  3068. this.w = source.w;
  3069. return this;
  3070. };
  3071. /**
  3072. * Updates the current Vector4 coordinates with the passed floats.
  3073. * Returns the updated Vector4.
  3074. */
  3075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3076. this.x = x;
  3077. this.y = y;
  3078. this.z = z;
  3079. this.w = w;
  3080. return this;
  3081. };
  3082. /**
  3083. * Updates the current Vector4 coordinates with the passed floats.
  3084. * Returns the updated Vector4.
  3085. */
  3086. Vector4.prototype.set = function (x, y, z, w) {
  3087. return this.copyFromFloats(x, y, z, w);
  3088. };
  3089. // Statics
  3090. /**
  3091. * Returns a new Vector4 set from the starting index of the passed array.
  3092. */
  3093. Vector4.FromArray = function (array, offset) {
  3094. if (!offset) {
  3095. offset = 0;
  3096. }
  3097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3098. };
  3099. /**
  3100. * Updates the passed vector "result" from the starting index of the passed array.
  3101. */
  3102. Vector4.FromArrayToRef = function (array, offset, result) {
  3103. result.x = array[offset];
  3104. result.y = array[offset + 1];
  3105. result.z = array[offset + 2];
  3106. result.w = array[offset + 3];
  3107. };
  3108. /**
  3109. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3110. */
  3111. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3112. Vector4.FromArrayToRef(array, offset, result);
  3113. };
  3114. /**
  3115. * Updates the passed vector "result" coordinates from the passed floats.
  3116. */
  3117. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3118. result.x = x;
  3119. result.y = y;
  3120. result.z = z;
  3121. result.w = w;
  3122. };
  3123. /**
  3124. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3125. */
  3126. Vector4.Zero = function () {
  3127. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3128. };
  3129. /**
  3130. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3131. */
  3132. Vector4.One = function () {
  3133. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3134. };
  3135. /**
  3136. * Returns a new normalized Vector4 from the passed one.
  3137. */
  3138. Vector4.Normalize = function (vector) {
  3139. var result = Vector4.Zero();
  3140. Vector4.NormalizeToRef(vector, result);
  3141. return result;
  3142. };
  3143. /**
  3144. * Updates the passed vector "result" from the normalization of the passed one.
  3145. */
  3146. Vector4.NormalizeToRef = function (vector, result) {
  3147. result.copyFrom(vector);
  3148. result.normalize();
  3149. };
  3150. Vector4.Minimize = function (left, right) {
  3151. var min = left.clone();
  3152. min.MinimizeInPlace(right);
  3153. return min;
  3154. };
  3155. Vector4.Maximize = function (left, right) {
  3156. var max = left.clone();
  3157. max.MaximizeInPlace(right);
  3158. return max;
  3159. };
  3160. /**
  3161. * Returns the distance (float) between the vectors "value1" and "value2".
  3162. */
  3163. Vector4.Distance = function (value1, value2) {
  3164. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3165. };
  3166. /**
  3167. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3168. */
  3169. Vector4.DistanceSquared = function (value1, value2) {
  3170. var x = value1.x - value2.x;
  3171. var y = value1.y - value2.y;
  3172. var z = value1.z - value2.z;
  3173. var w = value1.w - value2.w;
  3174. return (x * x) + (y * y) + (z * z) + (w * w);
  3175. };
  3176. /**
  3177. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3178. */
  3179. Vector4.Center = function (value1, value2) {
  3180. var center = value1.add(value2);
  3181. center.scaleInPlace(0.5);
  3182. return center;
  3183. };
  3184. /**
  3185. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3186. * This methods computes transformed normalized direction vectors only.
  3187. */
  3188. Vector4.TransformNormal = function (vector, transformation) {
  3189. var result = Vector4.Zero();
  3190. Vector4.TransformNormalToRef(vector, transformation, result);
  3191. return result;
  3192. };
  3193. /**
  3194. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3195. * This methods computes transformed normalized direction vectors only.
  3196. */
  3197. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3198. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3199. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3200. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3201. result.x = x;
  3202. result.y = y;
  3203. result.z = z;
  3204. result.w = vector.w;
  3205. };
  3206. /**
  3207. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3208. * This methods computes transformed normalized direction vectors only.
  3209. */
  3210. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3211. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3212. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3213. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3214. result.w = w;
  3215. };
  3216. return Vector4;
  3217. }());
  3218. BABYLON.Vector4 = Vector4;
  3219. var Size = /** @class */ (function () {
  3220. /**
  3221. * Creates a Size object from the passed width and height (floats).
  3222. */
  3223. function Size(width, height) {
  3224. this.width = width;
  3225. this.height = height;
  3226. }
  3227. // Returns a string with the Size width and height.
  3228. Size.prototype.toString = function () {
  3229. return "{W: " + this.width + ", H: " + this.height + "}";
  3230. };
  3231. /**
  3232. * Returns the string "Size"
  3233. */
  3234. Size.prototype.getClassName = function () {
  3235. return "Size";
  3236. };
  3237. /**
  3238. * Returns the Size hash code.
  3239. */
  3240. Size.prototype.getHashCode = function () {
  3241. var hash = this.width || 0;
  3242. hash = (hash * 397) ^ (this.height || 0);
  3243. return hash;
  3244. };
  3245. /**
  3246. * Updates the current size from the passed one.
  3247. * Returns the updated Size.
  3248. */
  3249. Size.prototype.copyFrom = function (src) {
  3250. this.width = src.width;
  3251. this.height = src.height;
  3252. };
  3253. /**
  3254. * Updates in place the current Size from the passed floats.
  3255. * Returns the updated Size.
  3256. */
  3257. Size.prototype.copyFromFloats = function (width, height) {
  3258. this.width = width;
  3259. this.height = height;
  3260. return this;
  3261. };
  3262. /**
  3263. * Updates in place the current Size from the passed floats.
  3264. * Returns the updated Size.
  3265. */
  3266. Size.prototype.set = function (width, height) {
  3267. return this.copyFromFloats(width, height);
  3268. };
  3269. /**
  3270. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3271. */
  3272. Size.prototype.multiplyByFloats = function (w, h) {
  3273. return new Size(this.width * w, this.height * h);
  3274. };
  3275. /**
  3276. * Returns a new Size copied from the passed one.
  3277. */
  3278. Size.prototype.clone = function () {
  3279. return new Size(this.width, this.height);
  3280. };
  3281. /**
  3282. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3283. */
  3284. Size.prototype.equals = function (other) {
  3285. if (!other) {
  3286. return false;
  3287. }
  3288. return (this.width === other.width) && (this.height === other.height);
  3289. };
  3290. Object.defineProperty(Size.prototype, "surface", {
  3291. /**
  3292. * Returns the surface of the Size : width * height (float).
  3293. */
  3294. get: function () {
  3295. return this.width * this.height;
  3296. },
  3297. enumerable: true,
  3298. configurable: true
  3299. });
  3300. /**
  3301. * Returns a new Size set to (0.0, 0.0)
  3302. */
  3303. Size.Zero = function () {
  3304. return new Size(0.0, 0.0);
  3305. };
  3306. /**
  3307. * Returns a new Size set as the addition result of the current Size and the passed one.
  3308. */
  3309. Size.prototype.add = function (otherSize) {
  3310. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3311. return r;
  3312. };
  3313. /**
  3314. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3315. */
  3316. Size.prototype.subtract = function (otherSize) {
  3317. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3318. return r;
  3319. };
  3320. /**
  3321. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3322. */
  3323. Size.Lerp = function (start, end, amount) {
  3324. var w = start.width + ((end.width - start.width) * amount);
  3325. var h = start.height + ((end.height - start.height) * amount);
  3326. return new Size(w, h);
  3327. };
  3328. return Size;
  3329. }());
  3330. BABYLON.Size = Size;
  3331. var Quaternion = /** @class */ (function () {
  3332. /**
  3333. * Creates a new Quaternion from the passed floats.
  3334. */
  3335. function Quaternion(x, y, z, w) {
  3336. if (x === void 0) { x = 0.0; }
  3337. if (y === void 0) { y = 0.0; }
  3338. if (z === void 0) { z = 0.0; }
  3339. if (w === void 0) { w = 1.0; }
  3340. this.x = x;
  3341. this.y = y;
  3342. this.z = z;
  3343. this.w = w;
  3344. }
  3345. /**
  3346. * Returns a string with the Quaternion coordinates.
  3347. */
  3348. Quaternion.prototype.toString = function () {
  3349. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3350. };
  3351. /**
  3352. * Returns the string "Quaternion".
  3353. */
  3354. Quaternion.prototype.getClassName = function () {
  3355. return "Quaternion";
  3356. };
  3357. /**
  3358. * Returns the Quaternion hash code.
  3359. */
  3360. Quaternion.prototype.getHashCode = function () {
  3361. var hash = this.x || 0;
  3362. hash = (hash * 397) ^ (this.y || 0);
  3363. hash = (hash * 397) ^ (this.z || 0);
  3364. hash = (hash * 397) ^ (this.w || 0);
  3365. return hash;
  3366. };
  3367. /**
  3368. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3369. */
  3370. Quaternion.prototype.asArray = function () {
  3371. return [this.x, this.y, this.z, this.w];
  3372. };
  3373. /**
  3374. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3375. */
  3376. Quaternion.prototype.equals = function (otherQuaternion) {
  3377. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3378. };
  3379. /**
  3380. * Returns a new Quaternion copied from the current one.
  3381. */
  3382. Quaternion.prototype.clone = function () {
  3383. return new Quaternion(this.x, this.y, this.z, this.w);
  3384. };
  3385. /**
  3386. * Updates the current Quaternion from the passed one coordinates.
  3387. * Returns the updated Quaterion.
  3388. */
  3389. Quaternion.prototype.copyFrom = function (other) {
  3390. this.x = other.x;
  3391. this.y = other.y;
  3392. this.z = other.z;
  3393. this.w = other.w;
  3394. return this;
  3395. };
  3396. /**
  3397. * Updates the current Quaternion from the passed float coordinates.
  3398. * Returns the updated Quaterion.
  3399. */
  3400. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3401. this.x = x;
  3402. this.y = y;
  3403. this.z = z;
  3404. this.w = w;
  3405. return this;
  3406. };
  3407. /**
  3408. * Updates the current Quaternion from the passed float coordinates.
  3409. * Returns the updated Quaterion.
  3410. */
  3411. Quaternion.prototype.set = function (x, y, z, w) {
  3412. return this.copyFromFloats(x, y, z, w);
  3413. };
  3414. /**
  3415. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3416. */
  3417. Quaternion.prototype.add = function (other) {
  3418. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3419. };
  3420. /**
  3421. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3422. */
  3423. Quaternion.prototype.subtract = function (other) {
  3424. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3425. };
  3426. /**
  3427. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3428. */
  3429. Quaternion.prototype.scale = function (value) {
  3430. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3431. };
  3432. /**
  3433. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3434. */
  3435. Quaternion.prototype.multiply = function (q1) {
  3436. var result = new Quaternion(0, 0, 0, 1.0);
  3437. this.multiplyToRef(q1, result);
  3438. return result;
  3439. };
  3440. /**
  3441. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3442. * Returns the current Quaternion.
  3443. */
  3444. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3445. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3446. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3447. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3448. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3449. result.copyFromFloats(x, y, z, w);
  3450. return this;
  3451. };
  3452. /**
  3453. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3454. * Returns the updated Quaternion.
  3455. */
  3456. Quaternion.prototype.multiplyInPlace = function (q1) {
  3457. this.multiplyToRef(q1, this);
  3458. return this;
  3459. };
  3460. /**
  3461. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3462. * Returns the current Quaternion.
  3463. */
  3464. Quaternion.prototype.conjugateToRef = function (ref) {
  3465. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3466. return this;
  3467. };
  3468. /**
  3469. * Conjugates in place the current Quaternion.
  3470. * Returns the updated Quaternion.
  3471. */
  3472. Quaternion.prototype.conjugateInPlace = function () {
  3473. this.x *= -1;
  3474. this.y *= -1;
  3475. this.z *= -1;
  3476. return this;
  3477. };
  3478. /**
  3479. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3480. */
  3481. Quaternion.prototype.conjugate = function () {
  3482. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3483. return result;
  3484. };
  3485. /**
  3486. * Returns the Quaternion length (float).
  3487. */
  3488. Quaternion.prototype.length = function () {
  3489. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3490. };
  3491. /**
  3492. * Normalize in place the current Quaternion.
  3493. * Returns the updated Quaternion.
  3494. */
  3495. Quaternion.prototype.normalize = function () {
  3496. var length = 1.0 / this.length();
  3497. this.x *= length;
  3498. this.y *= length;
  3499. this.z *= length;
  3500. this.w *= length;
  3501. return this;
  3502. };
  3503. /**
  3504. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3505. */
  3506. Quaternion.prototype.toEulerAngles = function (order) {
  3507. if (order === void 0) { order = "YZX"; }
  3508. var result = Vector3.Zero();
  3509. this.toEulerAnglesToRef(result, order);
  3510. return result;
  3511. };
  3512. /**
  3513. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3514. * Returns the current Quaternion.
  3515. */
  3516. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3517. if (order === void 0) { order = "YZX"; }
  3518. var qz = this.z;
  3519. var qx = this.x;
  3520. var qy = this.y;
  3521. var qw = this.w;
  3522. var sqw = qw * qw;
  3523. var sqz = qz * qz;
  3524. var sqx = qx * qx;
  3525. var sqy = qy * qy;
  3526. var zAxisY = qy * qz - qx * qw;
  3527. var limit = .4999999;
  3528. if (zAxisY < -limit) {
  3529. result.y = 2 * Math.atan2(qy, qw);
  3530. result.x = Math.PI / 2;
  3531. result.z = 0;
  3532. }
  3533. else if (zAxisY > limit) {
  3534. result.y = 2 * Math.atan2(qy, qw);
  3535. result.x = -Math.PI / 2;
  3536. result.z = 0;
  3537. }
  3538. else {
  3539. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3540. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3541. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3542. }
  3543. return this;
  3544. };
  3545. /**
  3546. * Updates the passed rotation matrix with the current Quaternion values.
  3547. * Returns the current Quaternion.
  3548. */
  3549. Quaternion.prototype.toRotationMatrix = function (result) {
  3550. var xx = this.x * this.x;
  3551. var yy = this.y * this.y;
  3552. var zz = this.z * this.z;
  3553. var xy = this.x * this.y;
  3554. var zw = this.z * this.w;
  3555. var zx = this.z * this.x;
  3556. var yw = this.y * this.w;
  3557. var yz = this.y * this.z;
  3558. var xw = this.x * this.w;
  3559. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3560. result.m[1] = 2.0 * (xy + zw);
  3561. result.m[2] = 2.0 * (zx - yw);
  3562. result.m[3] = 0;
  3563. result.m[4] = 2.0 * (xy - zw);
  3564. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3565. result.m[6] = 2.0 * (yz + xw);
  3566. result.m[7] = 0;
  3567. result.m[8] = 2.0 * (zx + yw);
  3568. result.m[9] = 2.0 * (yz - xw);
  3569. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3570. result.m[11] = 0;
  3571. result.m[12] = 0;
  3572. result.m[13] = 0;
  3573. result.m[14] = 0;
  3574. result.m[15] = 1.0;
  3575. result._markAsUpdated();
  3576. return this;
  3577. };
  3578. /**
  3579. * Updates the current Quaternion from the passed rotation matrix values.
  3580. * Returns the updated Quaternion.
  3581. */
  3582. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3583. Quaternion.FromRotationMatrixToRef(matrix, this);
  3584. return this;
  3585. };
  3586. // Statics
  3587. /**
  3588. * Returns a new Quaternion set from the passed rotation matrix values.
  3589. */
  3590. Quaternion.FromRotationMatrix = function (matrix) {
  3591. var result = new Quaternion();
  3592. Quaternion.FromRotationMatrixToRef(matrix, result);
  3593. return result;
  3594. };
  3595. /**
  3596. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3597. */
  3598. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3599. var data = matrix.m;
  3600. var m11 = data[0], m12 = data[4], m13 = data[8];
  3601. var m21 = data[1], m22 = data[5], m23 = data[9];
  3602. var m31 = data[2], m32 = data[6], m33 = data[10];
  3603. var trace = m11 + m22 + m33;
  3604. var s;
  3605. if (trace > 0) {
  3606. s = 0.5 / Math.sqrt(trace + 1.0);
  3607. result.w = 0.25 / s;
  3608. result.x = (m32 - m23) * s;
  3609. result.y = (m13 - m31) * s;
  3610. result.z = (m21 - m12) * s;
  3611. }
  3612. else if (m11 > m22 && m11 > m33) {
  3613. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3614. result.w = (m32 - m23) / s;
  3615. result.x = 0.25 * s;
  3616. result.y = (m12 + m21) / s;
  3617. result.z = (m13 + m31) / s;
  3618. }
  3619. else if (m22 > m33) {
  3620. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3621. result.w = (m13 - m31) / s;
  3622. result.x = (m12 + m21) / s;
  3623. result.y = 0.25 * s;
  3624. result.z = (m23 + m32) / s;
  3625. }
  3626. else {
  3627. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3628. result.w = (m21 - m12) / s;
  3629. result.x = (m13 + m31) / s;
  3630. result.y = (m23 + m32) / s;
  3631. result.z = 0.25 * s;
  3632. }
  3633. };
  3634. /**
  3635. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3636. */
  3637. Quaternion.Zero = function () {
  3638. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3639. };
  3640. /**
  3641. * Returns a new Quaternion as the inverted current Quaternion.
  3642. */
  3643. Quaternion.Inverse = function (q) {
  3644. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3645. };
  3646. /**
  3647. * Returns the identity Quaternion.
  3648. */
  3649. Quaternion.Identity = function () {
  3650. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3651. };
  3652. Quaternion.IsIdentity = function (quaternion) {
  3653. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3654. };
  3655. /**
  3656. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3657. */
  3658. Quaternion.RotationAxis = function (axis, angle) {
  3659. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3660. };
  3661. /**
  3662. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3663. */
  3664. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3665. var sin = Math.sin(angle / 2);
  3666. axis.normalize();
  3667. result.w = Math.cos(angle / 2);
  3668. result.x = axis.x * sin;
  3669. result.y = axis.y * sin;
  3670. result.z = axis.z * sin;
  3671. return result;
  3672. };
  3673. /**
  3674. * Retuns a new Quaternion set from the starting index of the passed array.
  3675. */
  3676. Quaternion.FromArray = function (array, offset) {
  3677. if (!offset) {
  3678. offset = 0;
  3679. }
  3680. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3681. };
  3682. /**
  3683. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3684. */
  3685. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3686. var q = new Quaternion();
  3687. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3688. return q;
  3689. };
  3690. /**
  3691. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3692. */
  3693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3695. var halfRoll = roll * 0.5;
  3696. var halfPitch = pitch * 0.5;
  3697. var halfYaw = yaw * 0.5;
  3698. var sinRoll = Math.sin(halfRoll);
  3699. var cosRoll = Math.cos(halfRoll);
  3700. var sinPitch = Math.sin(halfPitch);
  3701. var cosPitch = Math.cos(halfPitch);
  3702. var sinYaw = Math.sin(halfYaw);
  3703. var cosYaw = Math.cos(halfYaw);
  3704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3708. };
  3709. /**
  3710. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3711. */
  3712. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3713. var result = new Quaternion();
  3714. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3715. return result;
  3716. };
  3717. /**
  3718. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3719. */
  3720. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3721. // Produces a quaternion from Euler angles in the z-x-z orientation
  3722. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3723. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3724. var halfBeta = beta * 0.5;
  3725. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3726. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3727. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3728. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3729. };
  3730. /**
  3731. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3732. * cf to Vector3.RotationFromAxis() documentation.
  3733. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3734. */
  3735. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3736. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3737. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3738. return quat;
  3739. };
  3740. /**
  3741. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3742. * cf to Vector3.RotationFromAxis() documentation.
  3743. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3744. */
  3745. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3746. var rotMat = MathTmp.Matrix[0];
  3747. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3748. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3749. };
  3750. Quaternion.Slerp = function (left, right, amount) {
  3751. var result = Quaternion.Identity();
  3752. Quaternion.SlerpToRef(left, right, amount, result);
  3753. return result;
  3754. };
  3755. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3756. var num2;
  3757. var num3;
  3758. var num = amount;
  3759. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3760. var flag = false;
  3761. if (num4 < 0) {
  3762. flag = true;
  3763. num4 = -num4;
  3764. }
  3765. if (num4 > 0.999999) {
  3766. num3 = 1 - num;
  3767. num2 = flag ? -num : num;
  3768. }
  3769. else {
  3770. var num5 = Math.acos(num4);
  3771. var num6 = (1.0 / Math.sin(num5));
  3772. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3773. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3774. }
  3775. result.x = (num3 * left.x) + (num2 * right.x);
  3776. result.y = (num3 * left.y) + (num2 * right.y);
  3777. result.z = (num3 * left.z) + (num2 * right.z);
  3778. result.w = (num3 * left.w) + (num2 * right.w);
  3779. };
  3780. /**
  3781. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3782. */
  3783. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3784. var squared = amount * amount;
  3785. var cubed = amount * squared;
  3786. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3787. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3788. var part3 = (cubed - (2.0 * squared)) + amount;
  3789. var part4 = cubed - squared;
  3790. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3791. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3792. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3793. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3794. return new Quaternion(x, y, z, w);
  3795. };
  3796. return Quaternion;
  3797. }());
  3798. BABYLON.Quaternion = Quaternion;
  3799. var Matrix = /** @class */ (function () {
  3800. function Matrix() {
  3801. this._isIdentity = false;
  3802. this._isIdentityDirty = true;
  3803. this.m = new Float32Array(16);
  3804. this._markAsUpdated();
  3805. }
  3806. Matrix.prototype._markAsUpdated = function () {
  3807. this.updateFlag = Matrix._updateFlagSeed++;
  3808. this._isIdentityDirty = true;
  3809. };
  3810. // Properties
  3811. /**
  3812. * Boolean : True is the matrix is the identity matrix
  3813. */
  3814. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3815. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3816. if (this._isIdentityDirty) {
  3817. this._isIdentityDirty = false;
  3818. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3819. this._isIdentity = false;
  3820. }
  3821. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3822. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3823. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3824. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3825. this._isIdentity = false;
  3826. }
  3827. else {
  3828. this._isIdentity = true;
  3829. }
  3830. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3831. this._isIdentity = false;
  3832. }
  3833. }
  3834. return this._isIdentity;
  3835. };
  3836. /**
  3837. * Returns the matrix determinant (float).
  3838. */
  3839. Matrix.prototype.determinant = function () {
  3840. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3841. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3842. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3843. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3844. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3845. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3846. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3847. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3848. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3849. };
  3850. // Methods
  3851. /**
  3852. * Returns the matrix underlying array.
  3853. */
  3854. Matrix.prototype.toArray = function () {
  3855. return this.m;
  3856. };
  3857. /**
  3858. * Returns the matrix underlying array.
  3859. */
  3860. Matrix.prototype.asArray = function () {
  3861. return this.toArray();
  3862. };
  3863. /**
  3864. * Inverts in place the Matrix.
  3865. * Returns the Matrix inverted.
  3866. */
  3867. Matrix.prototype.invert = function () {
  3868. this.invertToRef(this);
  3869. return this;
  3870. };
  3871. /**
  3872. * Sets all the matrix elements to zero.
  3873. * Returns the Matrix.
  3874. */
  3875. Matrix.prototype.reset = function () {
  3876. for (var index = 0; index < 16; index++) {
  3877. this.m[index] = 0.0;
  3878. }
  3879. this._markAsUpdated();
  3880. return this;
  3881. };
  3882. /**
  3883. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3884. */
  3885. Matrix.prototype.add = function (other) {
  3886. var result = new Matrix();
  3887. this.addToRef(other, result);
  3888. return result;
  3889. };
  3890. /**
  3891. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3892. * Returns the Matrix.
  3893. */
  3894. Matrix.prototype.addToRef = function (other, result) {
  3895. for (var index = 0; index < 16; index++) {
  3896. result.m[index] = this.m[index] + other.m[index];
  3897. }
  3898. result._markAsUpdated();
  3899. return this;
  3900. };
  3901. /**
  3902. * Adds in place the passed matrix to the current Matrix.
  3903. * Returns the updated Matrix.
  3904. */
  3905. Matrix.prototype.addToSelf = function (other) {
  3906. for (var index = 0; index < 16; index++) {
  3907. this.m[index] += other.m[index];
  3908. }
  3909. this._markAsUpdated();
  3910. return this;
  3911. };
  3912. /**
  3913. * Sets the passed matrix with the current inverted Matrix.
  3914. * Returns the unmodified current Matrix.
  3915. */
  3916. Matrix.prototype.invertToRef = function (other) {
  3917. var l1 = this.m[0];
  3918. var l2 = this.m[1];
  3919. var l3 = this.m[2];
  3920. var l4 = this.m[3];
  3921. var l5 = this.m[4];
  3922. var l6 = this.m[5];
  3923. var l7 = this.m[6];
  3924. var l8 = this.m[7];
  3925. var l9 = this.m[8];
  3926. var l10 = this.m[9];
  3927. var l11 = this.m[10];
  3928. var l12 = this.m[11];
  3929. var l13 = this.m[12];
  3930. var l14 = this.m[13];
  3931. var l15 = this.m[14];
  3932. var l16 = this.m[15];
  3933. var l17 = (l11 * l16) - (l12 * l15);
  3934. var l18 = (l10 * l16) - (l12 * l14);
  3935. var l19 = (l10 * l15) - (l11 * l14);
  3936. var l20 = (l9 * l16) - (l12 * l13);
  3937. var l21 = (l9 * l15) - (l11 * l13);
  3938. var l22 = (l9 * l14) - (l10 * l13);
  3939. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3940. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3941. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3942. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3943. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3944. var l28 = (l7 * l16) - (l8 * l15);
  3945. var l29 = (l6 * l16) - (l8 * l14);
  3946. var l30 = (l6 * l15) - (l7 * l14);
  3947. var l31 = (l5 * l16) - (l8 * l13);
  3948. var l32 = (l5 * l15) - (l7 * l13);
  3949. var l33 = (l5 * l14) - (l6 * l13);
  3950. var l34 = (l7 * l12) - (l8 * l11);
  3951. var l35 = (l6 * l12) - (l8 * l10);
  3952. var l36 = (l6 * l11) - (l7 * l10);
  3953. var l37 = (l5 * l12) - (l8 * l9);
  3954. var l38 = (l5 * l11) - (l7 * l9);
  3955. var l39 = (l5 * l10) - (l6 * l9);
  3956. other.m[0] = l23 * l27;
  3957. other.m[4] = l24 * l27;
  3958. other.m[8] = l25 * l27;
  3959. other.m[12] = l26 * l27;
  3960. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3961. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3962. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3963. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3964. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3965. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3966. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3967. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3968. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3969. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3970. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3971. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3972. other._markAsUpdated();
  3973. return this;
  3974. };
  3975. /**
  3976. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3977. * Returns the updated Matrix.
  3978. */
  3979. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3980. this.m[12] = x;
  3981. this.m[13] = y;
  3982. this.m[14] = z;
  3983. this._markAsUpdated();
  3984. return this;
  3985. };
  3986. /**
  3987. * Inserts the translation vector in the current Matrix.
  3988. * Returns the updated Matrix.
  3989. */
  3990. Matrix.prototype.setTranslation = function (vector3) {
  3991. this.m[12] = vector3.x;
  3992. this.m[13] = vector3.y;
  3993. this.m[14] = vector3.z;
  3994. this._markAsUpdated();
  3995. return this;
  3996. };
  3997. /**
  3998. * Returns a new Vector3 as the extracted translation from the Matrix.
  3999. */
  4000. Matrix.prototype.getTranslation = function () {
  4001. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4002. };
  4003. /**
  4004. * Fill a Vector3 with the extracted translation from the Matrix.
  4005. */
  4006. Matrix.prototype.getTranslationToRef = function (result) {
  4007. result.x = this.m[12];
  4008. result.y = this.m[13];
  4009. result.z = this.m[14];
  4010. return this;
  4011. };
  4012. /**
  4013. * Remove rotation and scaling part from the Matrix.
  4014. * Returns the updated Matrix.
  4015. */
  4016. Matrix.prototype.removeRotationAndScaling = function () {
  4017. this.setRowFromFloats(0, 1, 0, 0, 0);
  4018. this.setRowFromFloats(1, 0, 1, 0, 0);
  4019. this.setRowFromFloats(2, 0, 0, 1, 0);
  4020. return this;
  4021. };
  4022. /**
  4023. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4024. */
  4025. Matrix.prototype.multiply = function (other) {
  4026. var result = new Matrix();
  4027. this.multiplyToRef(other, result);
  4028. return result;
  4029. };
  4030. /**
  4031. * Updates the current Matrix from the passed one values.
  4032. * Returns the updated Matrix.
  4033. */
  4034. Matrix.prototype.copyFrom = function (other) {
  4035. for (var index = 0; index < 16; index++) {
  4036. this.m[index] = other.m[index];
  4037. }
  4038. this._markAsUpdated();
  4039. return this;
  4040. };
  4041. /**
  4042. * Populates the passed array from the starting index with the Matrix values.
  4043. * Returns the Matrix.
  4044. */
  4045. Matrix.prototype.copyToArray = function (array, offset) {
  4046. if (offset === void 0) { offset = 0; }
  4047. for (var index = 0; index < 16; index++) {
  4048. array[offset + index] = this.m[index];
  4049. }
  4050. return this;
  4051. };
  4052. /**
  4053. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4054. */
  4055. Matrix.prototype.multiplyToRef = function (other, result) {
  4056. this.multiplyToArray(other, result.m, 0);
  4057. result._markAsUpdated();
  4058. return this;
  4059. };
  4060. /**
  4061. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4062. */
  4063. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4064. var tm0 = this.m[0];
  4065. var tm1 = this.m[1];
  4066. var tm2 = this.m[2];
  4067. var tm3 = this.m[3];
  4068. var tm4 = this.m[4];
  4069. var tm5 = this.m[5];
  4070. var tm6 = this.m[6];
  4071. var tm7 = this.m[7];
  4072. var tm8 = this.m[8];
  4073. var tm9 = this.m[9];
  4074. var tm10 = this.m[10];
  4075. var tm11 = this.m[11];
  4076. var tm12 = this.m[12];
  4077. var tm13 = this.m[13];
  4078. var tm14 = this.m[14];
  4079. var tm15 = this.m[15];
  4080. var om0 = other.m[0];
  4081. var om1 = other.m[1];
  4082. var om2 = other.m[2];
  4083. var om3 = other.m[3];
  4084. var om4 = other.m[4];
  4085. var om5 = other.m[5];
  4086. var om6 = other.m[6];
  4087. var om7 = other.m[7];
  4088. var om8 = other.m[8];
  4089. var om9 = other.m[9];
  4090. var om10 = other.m[10];
  4091. var om11 = other.m[11];
  4092. var om12 = other.m[12];
  4093. var om13 = other.m[13];
  4094. var om14 = other.m[14];
  4095. var om15 = other.m[15];
  4096. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4097. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4098. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4099. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4100. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4101. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4102. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4103. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4104. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4105. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4106. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4107. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4108. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4109. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4110. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4111. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4112. return this;
  4113. };
  4114. /**
  4115. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4116. */
  4117. Matrix.prototype.equals = function (value) {
  4118. return value &&
  4119. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4120. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4121. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4122. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4123. };
  4124. /**
  4125. * Returns a new Matrix from the current Matrix.
  4126. */
  4127. Matrix.prototype.clone = function () {
  4128. 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]);
  4129. };
  4130. /**
  4131. * Returns the string "Matrix"
  4132. */
  4133. Matrix.prototype.getClassName = function () {
  4134. return "Matrix";
  4135. };
  4136. /**
  4137. * Returns the Matrix hash code.
  4138. */
  4139. Matrix.prototype.getHashCode = function () {
  4140. var hash = this.m[0] || 0;
  4141. for (var i = 1; i < 16; i++) {
  4142. hash = (hash * 397) ^ (this.m[i] || 0);
  4143. }
  4144. return hash;
  4145. };
  4146. /**
  4147. * Decomposes the current Matrix into :
  4148. * - a scale vector3 passed as a reference to update,
  4149. * - a rotation quaternion passed as a reference to update,
  4150. * - a translation vector3 passed as a reference to update.
  4151. * Returns the boolean `true`.
  4152. */
  4153. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4154. translation.x = this.m[12];
  4155. translation.y = this.m[13];
  4156. translation.z = this.m[14];
  4157. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4158. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4159. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4160. if (this.determinant() <= 0) {
  4161. scale.y *= -1;
  4162. }
  4163. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4164. rotation.x = 0;
  4165. rotation.y = 0;
  4166. rotation.z = 0;
  4167. rotation.w = 1;
  4168. return false;
  4169. }
  4170. 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]);
  4171. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4172. return true;
  4173. };
  4174. /**
  4175. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4176. */
  4177. Matrix.prototype.getRotationMatrix = function () {
  4178. var result = Matrix.Identity();
  4179. this.getRotationMatrixToRef(result);
  4180. return result;
  4181. };
  4182. /**
  4183. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4184. * Returns the current Matrix.
  4185. */
  4186. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4187. var m = this.m;
  4188. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4189. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4190. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4191. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4192. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4193. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4194. 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);
  4195. return this;
  4196. };
  4197. // Statics
  4198. /**
  4199. * Returns a new Matrix set from the starting index of the passed array.
  4200. */
  4201. Matrix.FromArray = function (array, offset) {
  4202. var result = new Matrix();
  4203. if (!offset) {
  4204. offset = 0;
  4205. }
  4206. Matrix.FromArrayToRef(array, offset, result);
  4207. return result;
  4208. };
  4209. /**
  4210. * Sets the passed "result" matrix from the starting index of the passed array.
  4211. */
  4212. Matrix.FromArrayToRef = function (array, offset, result) {
  4213. for (var index = 0; index < 16; index++) {
  4214. result.m[index] = array[index + offset];
  4215. }
  4216. result._markAsUpdated();
  4217. };
  4218. /**
  4219. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4220. */
  4221. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4222. for (var index = 0; index < 16; index++) {
  4223. result.m[index] = array[index + offset] * scale;
  4224. }
  4225. result._markAsUpdated();
  4226. };
  4227. /**
  4228. * Sets the passed matrix "result" with the 16 passed floats.
  4229. */
  4230. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4231. result.m[0] = initialM11;
  4232. result.m[1] = initialM12;
  4233. result.m[2] = initialM13;
  4234. result.m[3] = initialM14;
  4235. result.m[4] = initialM21;
  4236. result.m[5] = initialM22;
  4237. result.m[6] = initialM23;
  4238. result.m[7] = initialM24;
  4239. result.m[8] = initialM31;
  4240. result.m[9] = initialM32;
  4241. result.m[10] = initialM33;
  4242. result.m[11] = initialM34;
  4243. result.m[12] = initialM41;
  4244. result.m[13] = initialM42;
  4245. result.m[14] = initialM43;
  4246. result.m[15] = initialM44;
  4247. result._markAsUpdated();
  4248. };
  4249. /**
  4250. * Returns the index-th row of the current matrix as a new Vector4.
  4251. */
  4252. Matrix.prototype.getRow = function (index) {
  4253. if (index < 0 || index > 3) {
  4254. return null;
  4255. }
  4256. var i = index * 4;
  4257. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4258. };
  4259. /**
  4260. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4261. * Returns the updated Matrix.
  4262. */
  4263. Matrix.prototype.setRow = function (index, row) {
  4264. if (index < 0 || index > 3) {
  4265. return this;
  4266. }
  4267. var i = index * 4;
  4268. this.m[i + 0] = row.x;
  4269. this.m[i + 1] = row.y;
  4270. this.m[i + 2] = row.z;
  4271. this.m[i + 3] = row.w;
  4272. this._markAsUpdated();
  4273. return this;
  4274. };
  4275. /**
  4276. * Compute the transpose of the matrix.
  4277. * Returns a new Matrix.
  4278. */
  4279. Matrix.prototype.transpose = function () {
  4280. return Matrix.Transpose(this);
  4281. };
  4282. /**
  4283. * Compute the transpose of the matrix.
  4284. * Returns the current matrix.
  4285. */
  4286. Matrix.prototype.transposeToRef = function (result) {
  4287. Matrix.TransposeToRef(this, result);
  4288. return this;
  4289. };
  4290. /**
  4291. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4292. * Returns the updated Matrix.
  4293. */
  4294. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4295. if (index < 0 || index > 3) {
  4296. return this;
  4297. }
  4298. var i = index * 4;
  4299. this.m[i + 0] = x;
  4300. this.m[i + 1] = y;
  4301. this.m[i + 2] = z;
  4302. this.m[i + 3] = w;
  4303. this._markAsUpdated();
  4304. return this;
  4305. };
  4306. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4307. /**
  4308. * Static identity matrix to be used as readonly matrix
  4309. * Must not be updated.
  4310. */
  4311. get: function () {
  4312. return Matrix._identityReadOnly;
  4313. },
  4314. enumerable: true,
  4315. configurable: true
  4316. });
  4317. /**
  4318. * Returns a new Matrix set from the 16 passed floats.
  4319. */
  4320. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4321. var result = new Matrix();
  4322. result.m[0] = initialM11;
  4323. result.m[1] = initialM12;
  4324. result.m[2] = initialM13;
  4325. result.m[3] = initialM14;
  4326. result.m[4] = initialM21;
  4327. result.m[5] = initialM22;
  4328. result.m[6] = initialM23;
  4329. result.m[7] = initialM24;
  4330. result.m[8] = initialM31;
  4331. result.m[9] = initialM32;
  4332. result.m[10] = initialM33;
  4333. result.m[11] = initialM34;
  4334. result.m[12] = initialM41;
  4335. result.m[13] = initialM42;
  4336. result.m[14] = initialM43;
  4337. result.m[15] = initialM44;
  4338. return result;
  4339. };
  4340. /**
  4341. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4342. */
  4343. Matrix.Compose = function (scale, rotation, translation) {
  4344. var result = Matrix.Identity();
  4345. Matrix.ComposeToRef(scale, rotation, translation, result);
  4346. return result;
  4347. };
  4348. /**
  4349. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4350. */
  4351. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4352. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4353. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4354. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4355. result.setTranslation(translation);
  4356. };
  4357. /**
  4358. * Returns a new indentity Matrix.
  4359. */
  4360. Matrix.Identity = function () {
  4361. 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);
  4362. };
  4363. /**
  4364. * Sets the passed "result" as an identity matrix.
  4365. */
  4366. Matrix.IdentityToRef = function (result) {
  4367. 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);
  4368. };
  4369. /**
  4370. * Returns a new zero Matrix.
  4371. */
  4372. Matrix.Zero = function () {
  4373. 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);
  4374. };
  4375. /**
  4376. * Returns a new rotation matrix for "angle" radians around the X axis.
  4377. */
  4378. Matrix.RotationX = function (angle) {
  4379. var result = new Matrix();
  4380. Matrix.RotationXToRef(angle, result);
  4381. return result;
  4382. };
  4383. /**
  4384. * Returns a new Matrix as the passed inverted one.
  4385. */
  4386. Matrix.Invert = function (source) {
  4387. var result = new Matrix();
  4388. source.invertToRef(result);
  4389. return result;
  4390. };
  4391. /**
  4392. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4393. */
  4394. Matrix.RotationXToRef = function (angle, result) {
  4395. var s = Math.sin(angle);
  4396. var c = Math.cos(angle);
  4397. result.m[0] = 1.0;
  4398. result.m[15] = 1.0;
  4399. result.m[5] = c;
  4400. result.m[10] = c;
  4401. result.m[9] = -s;
  4402. result.m[6] = s;
  4403. result.m[1] = 0.0;
  4404. result.m[2] = 0.0;
  4405. result.m[3] = 0.0;
  4406. result.m[4] = 0.0;
  4407. result.m[7] = 0.0;
  4408. result.m[8] = 0.0;
  4409. result.m[11] = 0.0;
  4410. result.m[12] = 0.0;
  4411. result.m[13] = 0.0;
  4412. result.m[14] = 0.0;
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4417. */
  4418. Matrix.RotationY = function (angle) {
  4419. var result = new Matrix();
  4420. Matrix.RotationYToRef(angle, result);
  4421. return result;
  4422. };
  4423. /**
  4424. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4425. */
  4426. Matrix.RotationYToRef = function (angle, result) {
  4427. var s = Math.sin(angle);
  4428. var c = Math.cos(angle);
  4429. result.m[5] = 1.0;
  4430. result.m[15] = 1.0;
  4431. result.m[0] = c;
  4432. result.m[2] = -s;
  4433. result.m[8] = s;
  4434. result.m[10] = c;
  4435. result.m[1] = 0.0;
  4436. result.m[3] = 0.0;
  4437. result.m[4] = 0.0;
  4438. result.m[6] = 0.0;
  4439. result.m[7] = 0.0;
  4440. result.m[9] = 0.0;
  4441. result.m[11] = 0.0;
  4442. result.m[12] = 0.0;
  4443. result.m[13] = 0.0;
  4444. result.m[14] = 0.0;
  4445. result._markAsUpdated();
  4446. };
  4447. /**
  4448. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4449. */
  4450. Matrix.RotationZ = function (angle) {
  4451. var result = new Matrix();
  4452. Matrix.RotationZToRef(angle, result);
  4453. return result;
  4454. };
  4455. /**
  4456. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4457. */
  4458. Matrix.RotationZToRef = function (angle, result) {
  4459. var s = Math.sin(angle);
  4460. var c = Math.cos(angle);
  4461. result.m[10] = 1.0;
  4462. result.m[15] = 1.0;
  4463. result.m[0] = c;
  4464. result.m[1] = s;
  4465. result.m[4] = -s;
  4466. result.m[5] = c;
  4467. result.m[2] = 0.0;
  4468. result.m[3] = 0.0;
  4469. result.m[6] = 0.0;
  4470. result.m[7] = 0.0;
  4471. result.m[8] = 0.0;
  4472. result.m[9] = 0.0;
  4473. result.m[11] = 0.0;
  4474. result.m[12] = 0.0;
  4475. result.m[13] = 0.0;
  4476. result.m[14] = 0.0;
  4477. result._markAsUpdated();
  4478. };
  4479. /**
  4480. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4481. */
  4482. Matrix.RotationAxis = function (axis, angle) {
  4483. var result = Matrix.Zero();
  4484. Matrix.RotationAxisToRef(axis, angle, result);
  4485. return result;
  4486. };
  4487. /**
  4488. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4489. */
  4490. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4491. var s = Math.sin(-angle);
  4492. var c = Math.cos(-angle);
  4493. var c1 = 1 - c;
  4494. axis.normalize();
  4495. result.m[0] = (axis.x * axis.x) * c1 + c;
  4496. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4497. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4498. result.m[3] = 0.0;
  4499. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4500. result.m[5] = (axis.y * axis.y) * c1 + c;
  4501. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4502. result.m[7] = 0.0;
  4503. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4504. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4505. result.m[10] = (axis.z * axis.z) * c1 + c;
  4506. result.m[11] = 0.0;
  4507. result.m[15] = 1.0;
  4508. result._markAsUpdated();
  4509. };
  4510. /**
  4511. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4512. */
  4513. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4514. var result = new Matrix();
  4515. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4516. return result;
  4517. };
  4518. /**
  4519. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4520. */
  4521. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4522. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4523. this._tempQuaternion.toRotationMatrix(result);
  4524. };
  4525. /**
  4526. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4527. */
  4528. Matrix.Scaling = function (x, y, z) {
  4529. var result = Matrix.Zero();
  4530. Matrix.ScalingToRef(x, y, z, result);
  4531. return result;
  4532. };
  4533. /**
  4534. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4535. */
  4536. Matrix.ScalingToRef = function (x, y, z, result) {
  4537. result.m[0] = x;
  4538. result.m[1] = 0.0;
  4539. result.m[2] = 0.0;
  4540. result.m[3] = 0.0;
  4541. result.m[4] = 0.0;
  4542. result.m[5] = y;
  4543. result.m[6] = 0.0;
  4544. result.m[7] = 0.0;
  4545. result.m[8] = 0.0;
  4546. result.m[9] = 0.0;
  4547. result.m[10] = z;
  4548. result.m[11] = 0.0;
  4549. result.m[12] = 0.0;
  4550. result.m[13] = 0.0;
  4551. result.m[14] = 0.0;
  4552. result.m[15] = 1.0;
  4553. result._markAsUpdated();
  4554. };
  4555. /**
  4556. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4557. */
  4558. Matrix.Translation = function (x, y, z) {
  4559. var result = Matrix.Identity();
  4560. Matrix.TranslationToRef(x, y, z, result);
  4561. return result;
  4562. };
  4563. /**
  4564. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4565. */
  4566. Matrix.TranslationToRef = function (x, y, z, result) {
  4567. 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);
  4568. };
  4569. /**
  4570. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4571. */
  4572. Matrix.Lerp = function (startValue, endValue, gradient) {
  4573. var result = Matrix.Zero();
  4574. for (var index = 0; index < 16; index++) {
  4575. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4576. }
  4577. result._markAsUpdated();
  4578. return result;
  4579. };
  4580. /**
  4581. * Returns a new Matrix whose values are computed by :
  4582. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4583. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4584. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4585. */
  4586. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4587. var startScale = new Vector3(0, 0, 0);
  4588. var startRotation = new Quaternion();
  4589. var startTranslation = new Vector3(0, 0, 0);
  4590. startValue.decompose(startScale, startRotation, startTranslation);
  4591. var endScale = new Vector3(0, 0, 0);
  4592. var endRotation = new Quaternion();
  4593. var endTranslation = new Vector3(0, 0, 0);
  4594. endValue.decompose(endScale, endRotation, endTranslation);
  4595. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4596. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4597. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4598. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4599. };
  4600. /**
  4601. * 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".
  4602. * This methods works for a Left-Handed system.
  4603. */
  4604. Matrix.LookAtLH = function (eye, target, up) {
  4605. var result = Matrix.Zero();
  4606. Matrix.LookAtLHToRef(eye, target, up, result);
  4607. return result;
  4608. };
  4609. /**
  4610. * 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".
  4611. * This methods works for a Left-Handed system.
  4612. */
  4613. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4614. // Z axis
  4615. target.subtractToRef(eye, this._zAxis);
  4616. this._zAxis.normalize();
  4617. // X axis
  4618. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4619. if (this._xAxis.lengthSquared() === 0) {
  4620. this._xAxis.x = 1.0;
  4621. }
  4622. else {
  4623. this._xAxis.normalize();
  4624. }
  4625. // Y axis
  4626. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4627. this._yAxis.normalize();
  4628. // Eye angles
  4629. var ex = -Vector3.Dot(this._xAxis, eye);
  4630. var ey = -Vector3.Dot(this._yAxis, eye);
  4631. var ez = -Vector3.Dot(this._zAxis, eye);
  4632. 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);
  4633. };
  4634. /**
  4635. * 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".
  4636. * This methods works for a Right-Handed system.
  4637. */
  4638. Matrix.LookAtRH = function (eye, target, up) {
  4639. var result = Matrix.Zero();
  4640. Matrix.LookAtRHToRef(eye, target, up, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * 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".
  4645. * This methods works for a Left-Handed system.
  4646. */
  4647. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4648. // Z axis
  4649. eye.subtractToRef(target, this._zAxis);
  4650. this._zAxis.normalize();
  4651. // X axis
  4652. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4653. if (this._xAxis.lengthSquared() === 0) {
  4654. this._xAxis.x = 1.0;
  4655. }
  4656. else {
  4657. this._xAxis.normalize();
  4658. }
  4659. // Y axis
  4660. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4661. this._yAxis.normalize();
  4662. // Eye angles
  4663. var ex = -Vector3.Dot(this._xAxis, eye);
  4664. var ey = -Vector3.Dot(this._yAxis, eye);
  4665. var ez = -Vector3.Dot(this._zAxis, eye);
  4666. 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);
  4667. };
  4668. /**
  4669. * 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.
  4670. */
  4671. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4672. var matrix = Matrix.Zero();
  4673. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4674. return matrix;
  4675. };
  4676. /**
  4677. * 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.
  4678. */
  4679. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4680. var n = znear;
  4681. var f = zfar;
  4682. var a = 2.0 / width;
  4683. var b = 2.0 / height;
  4684. var c = 2.0 / (f - n);
  4685. var d = -(f + n) / (f - n);
  4686. 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);
  4687. };
  4688. /**
  4689. * 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.
  4690. */
  4691. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4692. var matrix = Matrix.Zero();
  4693. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4694. return matrix;
  4695. };
  4696. /**
  4697. * 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.
  4698. */
  4699. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4700. var n = znear;
  4701. var f = zfar;
  4702. var a = 2.0 / (right - left);
  4703. var b = 2.0 / (top - bottom);
  4704. var c = 2.0 / (f - n);
  4705. var d = -(f + n) / (f - n);
  4706. var i0 = (left + right) / (left - right);
  4707. var i1 = (top + bottom) / (bottom - top);
  4708. 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);
  4709. };
  4710. /**
  4711. * 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.
  4712. */
  4713. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4714. var matrix = Matrix.Zero();
  4715. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4716. return matrix;
  4717. };
  4718. /**
  4719. * 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.
  4720. */
  4721. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4722. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4723. result.m[10] *= -1.0;
  4724. };
  4725. /**
  4726. * 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.
  4727. */
  4728. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4729. var matrix = Matrix.Zero();
  4730. var n = znear;
  4731. var f = zfar;
  4732. var a = 2.0 * n / width;
  4733. var b = 2.0 * n / height;
  4734. var c = (f + n) / (f - n);
  4735. var d = -2.0 * f * n / (f - n);
  4736. 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);
  4737. return matrix;
  4738. };
  4739. /**
  4740. * 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.
  4741. */
  4742. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4743. var matrix = Matrix.Zero();
  4744. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4745. return matrix;
  4746. };
  4747. /**
  4748. * 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.
  4749. */
  4750. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4751. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4752. var n = znear;
  4753. var f = zfar;
  4754. var t = 1.0 / (Math.tan(fov * 0.5));
  4755. var a = isVerticalFovFixed ? (t / aspect) : t;
  4756. var b = isVerticalFovFixed ? t : (t * aspect);
  4757. var c = (f + n) / (f - n);
  4758. var d = -2.0 * f * n / (f - n);
  4759. 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);
  4760. };
  4761. /**
  4762. * 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.
  4763. */
  4764. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4765. var matrix = Matrix.Zero();
  4766. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4767. return matrix;
  4768. };
  4769. /**
  4770. * 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.
  4771. */
  4772. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4773. //alternatively this could be expressed as:
  4774. // m = PerspectiveFovLHToRef
  4775. // m[10] *= -1.0;
  4776. // m[11] *= -1.0;
  4777. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4778. var n = znear;
  4779. var f = zfar;
  4780. var t = 1.0 / (Math.tan(fov * 0.5));
  4781. var a = isVerticalFovFixed ? (t / aspect) : t;
  4782. var b = isVerticalFovFixed ? t : (t * aspect);
  4783. var c = -(f + n) / (f - n);
  4784. var d = -2 * f * n / (f - n);
  4785. 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);
  4786. };
  4787. /**
  4788. * 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.
  4789. */
  4790. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4791. if (rightHanded === void 0) { rightHanded = false; }
  4792. var rightHandedFactor = rightHanded ? -1 : 1;
  4793. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4794. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4795. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4796. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4797. var xScale = 2.0 / (leftTan + rightTan);
  4798. var yScale = 2.0 / (upTan + downTan);
  4799. result.m[0] = xScale;
  4800. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4801. result.m[5] = yScale;
  4802. result.m[6] = result.m[7] = 0.0;
  4803. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4804. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4805. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4806. result.m[10] = -zfar / (znear - zfar);
  4807. result.m[11] = 1.0 * rightHandedFactor;
  4808. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4809. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4810. // result.m[14] = (znear * zfar) / (znear - zfar);
  4811. result._markAsUpdated();
  4812. };
  4813. /**
  4814. * Returns the final transformation matrix : world * view * projection * viewport
  4815. */
  4816. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4817. var cw = viewport.width;
  4818. var ch = viewport.height;
  4819. var cx = viewport.x;
  4820. var cy = viewport.y;
  4821. 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);
  4822. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4823. };
  4824. /**
  4825. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4826. */
  4827. Matrix.GetAsMatrix2x2 = function (matrix) {
  4828. return new Float32Array([
  4829. matrix.m[0], matrix.m[1],
  4830. matrix.m[4], matrix.m[5]
  4831. ]);
  4832. };
  4833. /**
  4834. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4835. */
  4836. Matrix.GetAsMatrix3x3 = function (matrix) {
  4837. return new Float32Array([
  4838. matrix.m[0], matrix.m[1], matrix.m[2],
  4839. matrix.m[4], matrix.m[5], matrix.m[6],
  4840. matrix.m[8], matrix.m[9], matrix.m[10]
  4841. ]);
  4842. };
  4843. /**
  4844. * Compute the transpose of the passed Matrix.
  4845. * Returns a new Matrix.
  4846. */
  4847. Matrix.Transpose = function (matrix) {
  4848. var result = new Matrix();
  4849. Matrix.TransposeToRef(matrix, result);
  4850. return result;
  4851. };
  4852. /**
  4853. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4854. */
  4855. Matrix.TransposeToRef = function (matrix, result) {
  4856. result.m[0] = matrix.m[0];
  4857. result.m[1] = matrix.m[4];
  4858. result.m[2] = matrix.m[8];
  4859. result.m[3] = matrix.m[12];
  4860. result.m[4] = matrix.m[1];
  4861. result.m[5] = matrix.m[5];
  4862. result.m[6] = matrix.m[9];
  4863. result.m[7] = matrix.m[13];
  4864. result.m[8] = matrix.m[2];
  4865. result.m[9] = matrix.m[6];
  4866. result.m[10] = matrix.m[10];
  4867. result.m[11] = matrix.m[14];
  4868. result.m[12] = matrix.m[3];
  4869. result.m[13] = matrix.m[7];
  4870. result.m[14] = matrix.m[11];
  4871. result.m[15] = matrix.m[15];
  4872. };
  4873. /**
  4874. * Returns a new Matrix as the reflection matrix across the passed plane.
  4875. */
  4876. Matrix.Reflection = function (plane) {
  4877. var matrix = new Matrix();
  4878. Matrix.ReflectionToRef(plane, matrix);
  4879. return matrix;
  4880. };
  4881. /**
  4882. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4883. */
  4884. Matrix.ReflectionToRef = function (plane, result) {
  4885. plane.normalize();
  4886. var x = plane.normal.x;
  4887. var y = plane.normal.y;
  4888. var z = plane.normal.z;
  4889. var temp = -2 * x;
  4890. var temp2 = -2 * y;
  4891. var temp3 = -2 * z;
  4892. result.m[0] = (temp * x) + 1;
  4893. result.m[1] = temp2 * x;
  4894. result.m[2] = temp3 * x;
  4895. result.m[3] = 0.0;
  4896. result.m[4] = temp * y;
  4897. result.m[5] = (temp2 * y) + 1;
  4898. result.m[6] = temp3 * y;
  4899. result.m[7] = 0.0;
  4900. result.m[8] = temp * z;
  4901. result.m[9] = temp2 * z;
  4902. result.m[10] = (temp3 * z) + 1;
  4903. result.m[11] = 0.0;
  4904. result.m[12] = temp * plane.d;
  4905. result.m[13] = temp2 * plane.d;
  4906. result.m[14] = temp3 * plane.d;
  4907. result.m[15] = 1.0;
  4908. result._markAsUpdated();
  4909. };
  4910. /**
  4911. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4912. */
  4913. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4914. result.m[0] = xaxis.x;
  4915. result.m[1] = xaxis.y;
  4916. result.m[2] = xaxis.z;
  4917. result.m[3] = 0.0;
  4918. result.m[4] = yaxis.x;
  4919. result.m[5] = yaxis.y;
  4920. result.m[6] = yaxis.z;
  4921. result.m[7] = 0.0;
  4922. result.m[8] = zaxis.x;
  4923. result.m[9] = zaxis.y;
  4924. result.m[10] = zaxis.z;
  4925. result.m[11] = 0.0;
  4926. result.m[12] = 0.0;
  4927. result.m[13] = 0.0;
  4928. result.m[14] = 0.0;
  4929. result.m[15] = 1.0;
  4930. result._markAsUpdated();
  4931. };
  4932. /**
  4933. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4934. */
  4935. Matrix.FromQuaternionToRef = function (quat, result) {
  4936. var xx = quat.x * quat.x;
  4937. var yy = quat.y * quat.y;
  4938. var zz = quat.z * quat.z;
  4939. var xy = quat.x * quat.y;
  4940. var zw = quat.z * quat.w;
  4941. var zx = quat.z * quat.x;
  4942. var yw = quat.y * quat.w;
  4943. var yz = quat.y * quat.z;
  4944. var xw = quat.x * quat.w;
  4945. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4946. result.m[1] = 2.0 * (xy + zw);
  4947. result.m[2] = 2.0 * (zx - yw);
  4948. result.m[3] = 0.0;
  4949. result.m[4] = 2.0 * (xy - zw);
  4950. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4951. result.m[6] = 2.0 * (yz + xw);
  4952. result.m[7] = 0.0;
  4953. result.m[8] = 2.0 * (zx + yw);
  4954. result.m[9] = 2.0 * (yz - xw);
  4955. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4956. result.m[11] = 0.0;
  4957. result.m[12] = 0.0;
  4958. result.m[13] = 0.0;
  4959. result.m[14] = 0.0;
  4960. result.m[15] = 1.0;
  4961. result._markAsUpdated();
  4962. };
  4963. Matrix._tempQuaternion = new Quaternion();
  4964. Matrix._xAxis = Vector3.Zero();
  4965. Matrix._yAxis = Vector3.Zero();
  4966. Matrix._zAxis = Vector3.Zero();
  4967. Matrix._updateFlagSeed = 0;
  4968. Matrix._identityReadOnly = Matrix.Identity();
  4969. return Matrix;
  4970. }());
  4971. BABYLON.Matrix = Matrix;
  4972. var Plane = /** @class */ (function () {
  4973. /**
  4974. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4975. */
  4976. function Plane(a, b, c, d) {
  4977. this.normal = new Vector3(a, b, c);
  4978. this.d = d;
  4979. }
  4980. /**
  4981. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4982. */
  4983. Plane.prototype.asArray = function () {
  4984. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4985. };
  4986. // Methods
  4987. /**
  4988. * Returns a new plane copied from the current Plane.
  4989. */
  4990. Plane.prototype.clone = function () {
  4991. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4992. };
  4993. /**
  4994. * Returns the string "Plane".
  4995. */
  4996. Plane.prototype.getClassName = function () {
  4997. return "Plane";
  4998. };
  4999. /**
  5000. * Returns the Plane hash code.
  5001. */
  5002. Plane.prototype.getHashCode = function () {
  5003. var hash = this.normal.getHashCode();
  5004. hash = (hash * 397) ^ (this.d || 0);
  5005. return hash;
  5006. };
  5007. /**
  5008. * Normalize the current Plane in place.
  5009. * Returns the updated Plane.
  5010. */
  5011. Plane.prototype.normalize = function () {
  5012. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5013. var magnitude = 0.0;
  5014. if (norm !== 0) {
  5015. magnitude = 1.0 / norm;
  5016. }
  5017. this.normal.x *= magnitude;
  5018. this.normal.y *= magnitude;
  5019. this.normal.z *= magnitude;
  5020. this.d *= magnitude;
  5021. return this;
  5022. };
  5023. /**
  5024. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5025. */
  5026. Plane.prototype.transform = function (transformation) {
  5027. var transposedMatrix = Matrix.Transpose(transformation);
  5028. var x = this.normal.x;
  5029. var y = this.normal.y;
  5030. var z = this.normal.z;
  5031. var d = this.d;
  5032. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5033. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5034. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5035. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5036. return new Plane(normalX, normalY, normalZ, finalD);
  5037. };
  5038. /**
  5039. * Returns the dot product (float) of the point coordinates and the plane normal.
  5040. */
  5041. Plane.prototype.dotCoordinate = function (point) {
  5042. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5043. };
  5044. /**
  5045. * Updates the current Plane from the plane defined by the three passed points.
  5046. * Returns the updated Plane.
  5047. */
  5048. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5049. var x1 = point2.x - point1.x;
  5050. var y1 = point2.y - point1.y;
  5051. var z1 = point2.z - point1.z;
  5052. var x2 = point3.x - point1.x;
  5053. var y2 = point3.y - point1.y;
  5054. var z2 = point3.z - point1.z;
  5055. var yz = (y1 * z2) - (z1 * y2);
  5056. var xz = (z1 * x2) - (x1 * z2);
  5057. var xy = (x1 * y2) - (y1 * x2);
  5058. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5059. var invPyth;
  5060. if (pyth !== 0) {
  5061. invPyth = 1.0 / pyth;
  5062. }
  5063. else {
  5064. invPyth = 0.0;
  5065. }
  5066. this.normal.x = yz * invPyth;
  5067. this.normal.y = xz * invPyth;
  5068. this.normal.z = xy * invPyth;
  5069. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5070. return this;
  5071. };
  5072. /**
  5073. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5074. */
  5075. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5076. var dot = Vector3.Dot(this.normal, direction);
  5077. return (dot <= epsilon);
  5078. };
  5079. /**
  5080. * Returns the signed distance (float) from the passed point to the Plane.
  5081. */
  5082. Plane.prototype.signedDistanceTo = function (point) {
  5083. return Vector3.Dot(point, this.normal) + this.d;
  5084. };
  5085. // Statics
  5086. /**
  5087. * Returns a new Plane from the passed array.
  5088. */
  5089. Plane.FromArray = function (array) {
  5090. return new Plane(array[0], array[1], array[2], array[3]);
  5091. };
  5092. /**
  5093. * Returns a new Plane defined by the three passed points.
  5094. */
  5095. Plane.FromPoints = function (point1, point2, point3) {
  5096. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5097. result.copyFromPoints(point1, point2, point3);
  5098. return result;
  5099. };
  5100. /**
  5101. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5102. * Note : the vector "normal" is updated because normalized.
  5103. */
  5104. Plane.FromPositionAndNormal = function (origin, normal) {
  5105. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5106. normal.normalize();
  5107. result.normal = normal;
  5108. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5109. return result;
  5110. };
  5111. /**
  5112. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5113. */
  5114. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5115. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5116. return Vector3.Dot(point, normal) + d;
  5117. };
  5118. return Plane;
  5119. }());
  5120. BABYLON.Plane = Plane;
  5121. var Viewport = /** @class */ (function () {
  5122. /**
  5123. * Creates a Viewport object located at (x, y) and sized (width, height).
  5124. */
  5125. function Viewport(x, y, width, height) {
  5126. this.x = x;
  5127. this.y = y;
  5128. this.width = width;
  5129. this.height = height;
  5130. }
  5131. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5132. if (renderWidthOrEngine.getRenderWidth) {
  5133. var engine = renderWidthOrEngine;
  5134. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5135. }
  5136. var renderWidth = renderWidthOrEngine;
  5137. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5138. };
  5139. /**
  5140. * Returns a new Viewport copied from the current one.
  5141. */
  5142. Viewport.prototype.clone = function () {
  5143. return new Viewport(this.x, this.y, this.width, this.height);
  5144. };
  5145. return Viewport;
  5146. }());
  5147. BABYLON.Viewport = Viewport;
  5148. var Frustum = /** @class */ (function () {
  5149. function Frustum() {
  5150. }
  5151. /**
  5152. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5153. */
  5154. Frustum.GetPlanes = function (transform) {
  5155. var frustumPlanes = [];
  5156. for (var index = 0; index < 6; index++) {
  5157. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5158. }
  5159. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5160. return frustumPlanes;
  5161. };
  5162. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5163. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5164. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5165. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5166. frustumPlane.d = transform.m[15] + transform.m[14];
  5167. frustumPlane.normalize();
  5168. };
  5169. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5170. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5171. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5172. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5173. frustumPlane.d = transform.m[15] - transform.m[14];
  5174. frustumPlane.normalize();
  5175. };
  5176. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5177. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5178. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5179. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5180. frustumPlane.d = transform.m[15] + transform.m[12];
  5181. frustumPlane.normalize();
  5182. };
  5183. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5184. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5185. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5186. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5187. frustumPlane.d = transform.m[15] - transform.m[12];
  5188. frustumPlane.normalize();
  5189. };
  5190. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5191. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5192. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5193. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5194. frustumPlane.d = transform.m[15] - transform.m[13];
  5195. frustumPlane.normalize();
  5196. };
  5197. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5198. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5199. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5200. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5201. frustumPlane.d = transform.m[15] + transform.m[13];
  5202. frustumPlane.normalize();
  5203. };
  5204. /**
  5205. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5206. */
  5207. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5208. // Near
  5209. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5210. // Far
  5211. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5212. // Left
  5213. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5214. // Right
  5215. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5216. // Top
  5217. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5218. // Bottom
  5219. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5220. };
  5221. return Frustum;
  5222. }());
  5223. BABYLON.Frustum = Frustum;
  5224. var Space;
  5225. (function (Space) {
  5226. Space[Space["LOCAL"] = 0] = "LOCAL";
  5227. Space[Space["WORLD"] = 1] = "WORLD";
  5228. Space[Space["BONE"] = 2] = "BONE";
  5229. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5230. var Axis = /** @class */ (function () {
  5231. function Axis() {
  5232. }
  5233. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5234. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5235. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5236. return Axis;
  5237. }());
  5238. BABYLON.Axis = Axis;
  5239. ;
  5240. var BezierCurve = /** @class */ (function () {
  5241. function BezierCurve() {
  5242. }
  5243. /**
  5244. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5245. */
  5246. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5247. // Extract X (which is equal to time here)
  5248. var f0 = 1 - 3 * x2 + 3 * x1;
  5249. var f1 = 3 * x2 - 6 * x1;
  5250. var f2 = 3 * x1;
  5251. var refinedT = t;
  5252. for (var i = 0; i < 5; i++) {
  5253. var refinedT2 = refinedT * refinedT;
  5254. var refinedT3 = refinedT2 * refinedT;
  5255. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5256. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5257. refinedT -= (x - t) * slope;
  5258. refinedT = Math.min(1, Math.max(0, refinedT));
  5259. }
  5260. // Resolve cubic bezier for the given x
  5261. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5262. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5263. Math.pow(refinedT, 3);
  5264. };
  5265. return BezierCurve;
  5266. }());
  5267. BABYLON.BezierCurve = BezierCurve;
  5268. var Orientation;
  5269. (function (Orientation) {
  5270. Orientation[Orientation["CW"] = 0] = "CW";
  5271. Orientation[Orientation["CCW"] = 1] = "CCW";
  5272. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5273. var Angle = /** @class */ (function () {
  5274. /**
  5275. * Creates an Angle object of "radians" radians (float).
  5276. */
  5277. function Angle(radians) {
  5278. var _this = this;
  5279. /**
  5280. * Returns the Angle value in degrees (float).
  5281. */
  5282. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5283. /**
  5284. * Returns the Angle value in radians (float).
  5285. */
  5286. this.radians = function () { return _this._radians; };
  5287. this._radians = radians;
  5288. if (this._radians < 0.0)
  5289. this._radians += (2.0 * Math.PI);
  5290. }
  5291. /**
  5292. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5293. */
  5294. Angle.BetweenTwoPoints = function (a, b) {
  5295. var delta = b.subtract(a);
  5296. var theta = Math.atan2(delta.y, delta.x);
  5297. return new Angle(theta);
  5298. };
  5299. /**
  5300. * Returns a new Angle object from the passed float in radians.
  5301. */
  5302. Angle.FromRadians = function (radians) {
  5303. return new Angle(radians);
  5304. };
  5305. /**
  5306. * Returns a new Angle object from the passed float in degrees.
  5307. */
  5308. Angle.FromDegrees = function (degrees) {
  5309. return new Angle(degrees * Math.PI / 180.0);
  5310. };
  5311. return Angle;
  5312. }());
  5313. BABYLON.Angle = Angle;
  5314. var Arc2 = /** @class */ (function () {
  5315. /**
  5316. * Creates an Arc object from the three passed points : start, middle and end.
  5317. */
  5318. function Arc2(startPoint, midPoint, endPoint) {
  5319. this.startPoint = startPoint;
  5320. this.midPoint = midPoint;
  5321. this.endPoint = endPoint;
  5322. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5323. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5324. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5325. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5326. 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);
  5327. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5328. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5329. var a1 = this.startAngle.degrees();
  5330. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5331. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5332. // angles correction
  5333. if (a2 - a1 > +180.0)
  5334. a2 -= 360.0;
  5335. if (a2 - a1 < -180.0)
  5336. a2 += 360.0;
  5337. if (a3 - a2 > +180.0)
  5338. a3 -= 360.0;
  5339. if (a3 - a2 < -180.0)
  5340. a3 += 360.0;
  5341. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5342. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5343. }
  5344. return Arc2;
  5345. }());
  5346. BABYLON.Arc2 = Arc2;
  5347. var Path2 = /** @class */ (function () {
  5348. /**
  5349. * Creates a Path2 object from the starting 2D coordinates x and y.
  5350. */
  5351. function Path2(x, y) {
  5352. this._points = new Array();
  5353. this._length = 0.0;
  5354. this.closed = false;
  5355. this._points.push(new Vector2(x, y));
  5356. }
  5357. /**
  5358. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5359. * Returns the updated Path2.
  5360. */
  5361. Path2.prototype.addLineTo = function (x, y) {
  5362. if (this.closed) {
  5363. //Tools.Error("cannot add lines to closed paths");
  5364. return this;
  5365. }
  5366. var newPoint = new Vector2(x, y);
  5367. var previousPoint = this._points[this._points.length - 1];
  5368. this._points.push(newPoint);
  5369. this._length += newPoint.subtract(previousPoint).length();
  5370. return this;
  5371. };
  5372. /**
  5373. * 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.
  5374. * Returns the updated Path2.
  5375. */
  5376. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5377. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5378. if (this.closed) {
  5379. //Tools.Error("cannot add arcs to closed paths");
  5380. return this;
  5381. }
  5382. var startPoint = this._points[this._points.length - 1];
  5383. var midPoint = new Vector2(midX, midY);
  5384. var endPoint = new Vector2(endX, endY);
  5385. var arc = new Arc2(startPoint, midPoint, endPoint);
  5386. var increment = arc.angle.radians() / numberOfSegments;
  5387. if (arc.orientation === Orientation.CW)
  5388. increment *= -1;
  5389. var currentAngle = arc.startAngle.radians() + increment;
  5390. for (var i = 0; i < numberOfSegments; i++) {
  5391. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5392. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5393. this.addLineTo(x, y);
  5394. currentAngle += increment;
  5395. }
  5396. return this;
  5397. };
  5398. /**
  5399. * Closes the Path2.
  5400. * Returns the Path2.
  5401. */
  5402. Path2.prototype.close = function () {
  5403. this.closed = true;
  5404. return this;
  5405. };
  5406. /**
  5407. * Returns the Path2 total length (float).
  5408. */
  5409. Path2.prototype.length = function () {
  5410. var result = this._length;
  5411. if (!this.closed) {
  5412. var lastPoint = this._points[this._points.length - 1];
  5413. var firstPoint = this._points[0];
  5414. result += (firstPoint.subtract(lastPoint).length());
  5415. }
  5416. return result;
  5417. };
  5418. /**
  5419. * Returns the Path2 internal array of points.
  5420. */
  5421. Path2.prototype.getPoints = function () {
  5422. return this._points;
  5423. };
  5424. /**
  5425. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5426. */
  5427. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5428. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5429. //Tools.Error("normalized length position should be between 0 and 1.");
  5430. return Vector2.Zero();
  5431. }
  5432. var lengthPosition = normalizedLengthPosition * this.length();
  5433. var previousOffset = 0;
  5434. for (var i = 0; i < this._points.length; i++) {
  5435. var j = (i + 1) % this._points.length;
  5436. var a = this._points[i];
  5437. var b = this._points[j];
  5438. var bToA = b.subtract(a);
  5439. var nextOffset = (bToA.length() + previousOffset);
  5440. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5441. var dir = bToA.normalize();
  5442. var localOffset = lengthPosition - previousOffset;
  5443. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5444. }
  5445. previousOffset = nextOffset;
  5446. }
  5447. //Tools.Error("internal error");
  5448. return Vector2.Zero();
  5449. };
  5450. /**
  5451. * Returns a new Path2 starting at the coordinates (x, y).
  5452. */
  5453. Path2.StartingAt = function (x, y) {
  5454. return new Path2(x, y);
  5455. };
  5456. return Path2;
  5457. }());
  5458. BABYLON.Path2 = Path2;
  5459. var Path3D = /** @class */ (function () {
  5460. /**
  5461. * new Path3D(path, normal, raw)
  5462. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5463. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5464. * path : an array of Vector3, the curve axis of the Path3D
  5465. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5466. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5467. */
  5468. function Path3D(path, firstNormal, raw) {
  5469. if (firstNormal === void 0) { firstNormal = null; }
  5470. this.path = path;
  5471. this._curve = new Array();
  5472. this._distances = new Array();
  5473. this._tangents = new Array();
  5474. this._normals = new Array();
  5475. this._binormals = new Array();
  5476. for (var p = 0; p < path.length; p++) {
  5477. this._curve[p] = path[p].clone(); // hard copy
  5478. }
  5479. this._raw = raw || false;
  5480. this._compute(firstNormal);
  5481. }
  5482. /**
  5483. * Returns the Path3D array of successive Vector3 designing its curve.
  5484. */
  5485. Path3D.prototype.getCurve = function () {
  5486. return this._curve;
  5487. };
  5488. /**
  5489. * Returns an array populated with tangent vectors on each Path3D curve point.
  5490. */
  5491. Path3D.prototype.getTangents = function () {
  5492. return this._tangents;
  5493. };
  5494. /**
  5495. * Returns an array populated with normal vectors on each Path3D curve point.
  5496. */
  5497. Path3D.prototype.getNormals = function () {
  5498. return this._normals;
  5499. };
  5500. /**
  5501. * Returns an array populated with binormal vectors on each Path3D curve point.
  5502. */
  5503. Path3D.prototype.getBinormals = function () {
  5504. return this._binormals;
  5505. };
  5506. /**
  5507. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5508. */
  5509. Path3D.prototype.getDistances = function () {
  5510. return this._distances;
  5511. };
  5512. /**
  5513. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5514. * Returns the same object updated.
  5515. */
  5516. Path3D.prototype.update = function (path, firstNormal) {
  5517. if (firstNormal === void 0) { firstNormal = null; }
  5518. for (var p = 0; p < path.length; p++) {
  5519. this._curve[p].x = path[p].x;
  5520. this._curve[p].y = path[p].y;
  5521. this._curve[p].z = path[p].z;
  5522. }
  5523. this._compute(firstNormal);
  5524. return this;
  5525. };
  5526. // private function compute() : computes tangents, normals and binormals
  5527. Path3D.prototype._compute = function (firstNormal) {
  5528. var l = this._curve.length;
  5529. // first and last tangents
  5530. this._tangents[0] = this._getFirstNonNullVector(0);
  5531. if (!this._raw) {
  5532. this._tangents[0].normalize();
  5533. }
  5534. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5535. if (!this._raw) {
  5536. this._tangents[l - 1].normalize();
  5537. }
  5538. // normals and binormals at first point : arbitrary vector with _normalVector()
  5539. var tg0 = this._tangents[0];
  5540. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5541. this._normals[0] = pp0;
  5542. if (!this._raw) {
  5543. this._normals[0].normalize();
  5544. }
  5545. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5546. if (!this._raw) {
  5547. this._binormals[0].normalize();
  5548. }
  5549. this._distances[0] = 0.0;
  5550. // normals and binormals : next points
  5551. var prev; // previous vector (segment)
  5552. var cur; // current vector (segment)
  5553. var curTang; // current tangent
  5554. // previous normal
  5555. var prevBinor; // previous binormal
  5556. for (var i = 1; i < l; i++) {
  5557. // tangents
  5558. prev = this._getLastNonNullVector(i);
  5559. if (i < l - 1) {
  5560. cur = this._getFirstNonNullVector(i);
  5561. this._tangents[i] = prev.add(cur);
  5562. this._tangents[i].normalize();
  5563. }
  5564. this._distances[i] = this._distances[i - 1] + prev.length();
  5565. // normals and binormals
  5566. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5567. curTang = this._tangents[i];
  5568. prevBinor = this._binormals[i - 1];
  5569. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5570. if (!this._raw) {
  5571. this._normals[i].normalize();
  5572. }
  5573. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5574. if (!this._raw) {
  5575. this._binormals[i].normalize();
  5576. }
  5577. }
  5578. };
  5579. // private function getFirstNonNullVector(index)
  5580. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5581. Path3D.prototype._getFirstNonNullVector = function (index) {
  5582. var i = 1;
  5583. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5584. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5585. i++;
  5586. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5587. }
  5588. return nNVector;
  5589. };
  5590. // private function getLastNonNullVector(index)
  5591. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5592. Path3D.prototype._getLastNonNullVector = function (index) {
  5593. var i = 1;
  5594. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5595. while (nLVector.length() === 0 && index > i + 1) {
  5596. i++;
  5597. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5598. }
  5599. return nLVector;
  5600. };
  5601. // private function normalVector(v0, vt, va) :
  5602. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5603. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5604. Path3D.prototype._normalVector = function (v0, vt, va) {
  5605. var normal0;
  5606. var tgl = vt.length();
  5607. if (tgl === 0.0) {
  5608. tgl = 1.0;
  5609. }
  5610. if (va === undefined || va === null) {
  5611. var point;
  5612. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5613. point = new Vector3(0.0, -1.0, 0.0);
  5614. }
  5615. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5616. point = new Vector3(1.0, 0.0, 0.0);
  5617. }
  5618. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5619. point = new Vector3(0.0, 0.0, 1.0);
  5620. }
  5621. else {
  5622. point = Vector3.Zero();
  5623. }
  5624. normal0 = Vector3.Cross(vt, point);
  5625. }
  5626. else {
  5627. normal0 = Vector3.Cross(vt, va);
  5628. Vector3.CrossToRef(normal0, vt, normal0);
  5629. }
  5630. normal0.normalize();
  5631. return normal0;
  5632. };
  5633. return Path3D;
  5634. }());
  5635. BABYLON.Path3D = Path3D;
  5636. var Curve3 = /** @class */ (function () {
  5637. /**
  5638. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5639. * A Curve3 is designed from a series of successive Vector3.
  5640. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5641. */
  5642. function Curve3(points) {
  5643. this._length = 0.0;
  5644. this._points = points;
  5645. this._length = this._computeLength(points);
  5646. }
  5647. /**
  5648. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5649. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5650. * @param v1 (Vector3) the control point
  5651. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5652. * @param nbPoints (integer) the wanted number of points in the curve
  5653. */
  5654. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5655. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5656. var bez = new Array();
  5657. var equation = function (t, val0, val1, val2) {
  5658. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5659. return res;
  5660. };
  5661. for (var i = 0; i <= nbPoints; i++) {
  5662. 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)));
  5663. }
  5664. return new Curve3(bez);
  5665. };
  5666. /**
  5667. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5668. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5669. * @param v1 (Vector3) the first control point
  5670. * @param v2 (Vector3) the second control point
  5671. * @param v3 (Vector3) the end point of the Cubic Bezier
  5672. * @param nbPoints (integer) the wanted number of points in the curve
  5673. */
  5674. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5675. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5676. var bez = new Array();
  5677. var equation = function (t, val0, val1, val2, val3) {
  5678. 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;
  5679. return res;
  5680. };
  5681. for (var i = 0; i <= nbPoints; i++) {
  5682. 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)));
  5683. }
  5684. return new Curve3(bez);
  5685. };
  5686. /**
  5687. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5688. * @param p1 (Vector3) the origin point of the Hermite Spline
  5689. * @param t1 (Vector3) the tangent vector at the origin point
  5690. * @param p2 (Vector3) the end point of the Hermite Spline
  5691. * @param t2 (Vector3) the tangent vector at the end point
  5692. * @param nbPoints (integer) the wanted number of points in the curve
  5693. */
  5694. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5695. var hermite = new Array();
  5696. var step = 1.0 / nbPoints;
  5697. for (var i = 0; i <= nbPoints; i++) {
  5698. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5699. }
  5700. return new Curve3(hermite);
  5701. };
  5702. /**
  5703. * Returns a Curve3 object along a CatmullRom Spline curve :
  5704. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5705. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5706. */
  5707. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5708. var totalPoints = new Array();
  5709. totalPoints.push(points[0].clone());
  5710. Array.prototype.push.apply(totalPoints, points);
  5711. totalPoints.push(points[points.length - 1].clone());
  5712. var catmullRom = new Array();
  5713. var step = 1.0 / nbPoints;
  5714. var amount = 0.0;
  5715. for (var i = 0; i < totalPoints.length - 3; i++) {
  5716. amount = 0;
  5717. for (var c = 0; c < nbPoints; c++) {
  5718. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5719. amount += step;
  5720. }
  5721. }
  5722. i--;
  5723. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5724. return new Curve3(catmullRom);
  5725. };
  5726. /**
  5727. * Returns the Curve3 stored array of successive Vector3
  5728. */
  5729. Curve3.prototype.getPoints = function () {
  5730. return this._points;
  5731. };
  5732. /**
  5733. * Returns the computed length (float) of the curve.
  5734. */
  5735. Curve3.prototype.length = function () {
  5736. return this._length;
  5737. };
  5738. /**
  5739. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5740. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5741. * curveA and curveB keep unchanged.
  5742. */
  5743. Curve3.prototype.continue = function (curve) {
  5744. var lastPoint = this._points[this._points.length - 1];
  5745. var continuedPoints = this._points.slice();
  5746. var curvePoints = curve.getPoints();
  5747. for (var i = 1; i < curvePoints.length; i++) {
  5748. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5749. }
  5750. var continuedCurve = new Curve3(continuedPoints);
  5751. return continuedCurve;
  5752. };
  5753. Curve3.prototype._computeLength = function (path) {
  5754. var l = 0;
  5755. for (var i = 1; i < path.length; i++) {
  5756. l += (path[i].subtract(path[i - 1])).length();
  5757. }
  5758. return l;
  5759. };
  5760. return Curve3;
  5761. }());
  5762. BABYLON.Curve3 = Curve3;
  5763. // Vertex formats
  5764. var PositionNormalVertex = /** @class */ (function () {
  5765. function PositionNormalVertex(position, normal) {
  5766. if (position === void 0) { position = Vector3.Zero(); }
  5767. if (normal === void 0) { normal = Vector3.Up(); }
  5768. this.position = position;
  5769. this.normal = normal;
  5770. }
  5771. PositionNormalVertex.prototype.clone = function () {
  5772. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5773. };
  5774. return PositionNormalVertex;
  5775. }());
  5776. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5777. var PositionNormalTextureVertex = /** @class */ (function () {
  5778. function PositionNormalTextureVertex(position, normal, uv) {
  5779. if (position === void 0) { position = Vector3.Zero(); }
  5780. if (normal === void 0) { normal = Vector3.Up(); }
  5781. if (uv === void 0) { uv = Vector2.Zero(); }
  5782. this.position = position;
  5783. this.normal = normal;
  5784. this.uv = uv;
  5785. }
  5786. PositionNormalTextureVertex.prototype.clone = function () {
  5787. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5788. };
  5789. return PositionNormalTextureVertex;
  5790. }());
  5791. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5792. // Temporary pre-allocated objects for engine internal use
  5793. // usage in any internal function :
  5794. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5795. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5796. var Tmp = /** @class */ (function () {
  5797. function Tmp() {
  5798. }
  5799. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5800. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5801. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5802. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5803. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5804. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5805. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5806. Matrix.Zero(), Matrix.Zero(),
  5807. Matrix.Zero(), Matrix.Zero(),
  5808. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5809. return Tmp;
  5810. }());
  5811. BABYLON.Tmp = Tmp;
  5812. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5813. var MathTmp = /** @class */ (function () {
  5814. function MathTmp() {
  5815. }
  5816. MathTmp.Vector3 = [Vector3.Zero()];
  5817. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5818. MathTmp.Quaternion = [Quaternion.Zero()];
  5819. return MathTmp;
  5820. }());
  5821. })(BABYLON || (BABYLON = {}));
  5822. //# sourceMappingURL=babylon.math.js.map
  5823. var BABYLON;
  5824. (function (BABYLON) {
  5825. var Scalar = /** @class */ (function () {
  5826. function Scalar() {
  5827. }
  5828. /**
  5829. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5830. */
  5831. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5832. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5833. var num = a - b;
  5834. return -epsilon <= num && num <= epsilon;
  5835. };
  5836. /**
  5837. * Returns a string : the upper case translation of the number i to hexadecimal.
  5838. */
  5839. Scalar.ToHex = function (i) {
  5840. var str = i.toString(16);
  5841. if (i <= 15) {
  5842. return ("0" + str).toUpperCase();
  5843. }
  5844. return str.toUpperCase();
  5845. };
  5846. /**
  5847. * Returns -1 if value is negative and +1 is value is positive.
  5848. * Returns the value itself if it's equal to zero.
  5849. */
  5850. Scalar.Sign = function (value) {
  5851. value = +value; // convert to a number
  5852. if (value === 0 || isNaN(value))
  5853. return value;
  5854. return value > 0 ? 1 : -1;
  5855. };
  5856. /**
  5857. * Returns the value itself if it's between min and max.
  5858. * Returns min if the value is lower than min.
  5859. * Returns max if the value is greater than max.
  5860. */
  5861. Scalar.Clamp = function (value, min, max) {
  5862. if (min === void 0) { min = 0; }
  5863. if (max === void 0) { max = 1; }
  5864. return Math.min(max, Math.max(min, value));
  5865. };
  5866. /**
  5867. * Returns the log2 of value.
  5868. */
  5869. Scalar.Log2 = function (value) {
  5870. return Math.log(value) * Math.LOG2E;
  5871. };
  5872. /**
  5873. * Loops the value, so that it is never larger than length and never smaller than 0.
  5874. *
  5875. * This is similar to the modulo operator but it works with floating point numbers.
  5876. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5877. * With t = 5 and length = 2.5, the result would be 0.0.
  5878. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5879. */
  5880. Scalar.Repeat = function (value, length) {
  5881. return value - Math.floor(value / length) * length;
  5882. };
  5883. /**
  5884. * Normalize the value between 0.0 and 1.0 using min and max values
  5885. */
  5886. Scalar.Normalize = function (value, min, max) {
  5887. return (value - min) / (max - min);
  5888. };
  5889. /**
  5890. * Denormalize the value from 0.0 and 1.0 using min and max values
  5891. */
  5892. Scalar.Denormalize = function (normalized, min, max) {
  5893. return (normalized * (max - min) + min);
  5894. };
  5895. /**
  5896. * Calculates the shortest difference between two given angles given in degrees.
  5897. */
  5898. Scalar.DeltaAngle = function (current, target) {
  5899. var num = Scalar.Repeat(target - current, 360.0);
  5900. if (num > 180.0) {
  5901. num -= 360.0;
  5902. }
  5903. return num;
  5904. };
  5905. /**
  5906. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5907. *
  5908. * The returned value will move back and forth between 0 and length
  5909. */
  5910. Scalar.PingPong = function (tx, length) {
  5911. var t = Scalar.Repeat(tx, length * 2.0);
  5912. return length - Math.abs(t - length);
  5913. };
  5914. /**
  5915. * Interpolates between min and max with smoothing at the limits.
  5916. *
  5917. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5918. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5919. */
  5920. Scalar.SmoothStep = function (from, to, tx) {
  5921. var t = Scalar.Clamp(tx);
  5922. t = -2.0 * t * t * t + 3.0 * t * t;
  5923. return to * t + from * (1.0 - t);
  5924. };
  5925. /**
  5926. * Moves a value current towards target.
  5927. *
  5928. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5929. * Negative values of maxDelta pushes the value away from target.
  5930. */
  5931. Scalar.MoveTowards = function (current, target, maxDelta) {
  5932. var result = 0;
  5933. if (Math.abs(target - current) <= maxDelta) {
  5934. result = target;
  5935. }
  5936. else {
  5937. result = current + Scalar.Sign(target - current) * maxDelta;
  5938. }
  5939. return result;
  5940. };
  5941. /**
  5942. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5943. *
  5944. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5945. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5946. */
  5947. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5948. var num = Scalar.DeltaAngle(current, target);
  5949. var result = 0;
  5950. if (-maxDelta < num && num < maxDelta) {
  5951. result = target;
  5952. }
  5953. else {
  5954. target = current + num;
  5955. result = Scalar.MoveTowards(current, target, maxDelta);
  5956. }
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5961. */
  5962. Scalar.Lerp = function (start, end, amount) {
  5963. return start + ((end - start) * amount);
  5964. };
  5965. /**
  5966. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5967. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5968. */
  5969. Scalar.LerpAngle = function (start, end, amount) {
  5970. var num = Scalar.Repeat(end - start, 360.0);
  5971. if (num > 180.0) {
  5972. num -= 360.0;
  5973. }
  5974. return start + num * Scalar.Clamp(amount);
  5975. };
  5976. /**
  5977. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5978. */
  5979. Scalar.InverseLerp = function (a, b, value) {
  5980. var result = 0;
  5981. if (a != b) {
  5982. result = Scalar.Clamp((value - a) / (b - a));
  5983. }
  5984. else {
  5985. result = 0.0;
  5986. }
  5987. return result;
  5988. };
  5989. /**
  5990. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5991. */
  5992. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5993. var squared = amount * amount;
  5994. var cubed = amount * squared;
  5995. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5996. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5997. var part3 = (cubed - (2.0 * squared)) + amount;
  5998. var part4 = cubed - squared;
  5999. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6000. };
  6001. /**
  6002. * Returns a random float number between and min and max values
  6003. */
  6004. Scalar.RandomRange = function (min, max) {
  6005. if (min === max)
  6006. return min;
  6007. return ((Math.random() * (max - min)) + min);
  6008. };
  6009. /**
  6010. * This function returns percentage of a number in a given range.
  6011. *
  6012. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6013. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6014. */
  6015. Scalar.RangeToPercent = function (number, min, max) {
  6016. return ((number - min) / (max - min));
  6017. };
  6018. /**
  6019. * This function returns number that corresponds to the percentage in a given range.
  6020. *
  6021. * PercentToRange(0.34,0,100) will return 34.
  6022. */
  6023. Scalar.PercentToRange = function (percent, min, max) {
  6024. return ((max - min) * percent + min);
  6025. };
  6026. /**
  6027. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6028. * @param angle The angle to normalize in radian.
  6029. * @return The converted angle.
  6030. */
  6031. Scalar.NormalizeRadians = function (angle) {
  6032. // More precise but slower version kept for reference.
  6033. // angle = angle % Tools.TwoPi;
  6034. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6035. //if (angle > Math.PI) {
  6036. // angle -= Tools.TwoPi;
  6037. //}
  6038. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6039. return angle;
  6040. };
  6041. /**
  6042. * Two pi constants convenient for computation.
  6043. */
  6044. Scalar.TwoPi = Math.PI * 2;
  6045. return Scalar;
  6046. }());
  6047. BABYLON.Scalar = Scalar;
  6048. })(BABYLON || (BABYLON = {}));
  6049. //# sourceMappingURL=babylon.math.scalar.js.map
  6050. //# sourceMappingURL=babylon.mixins.js.map
  6051. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6052. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6053. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6054. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6055. //# sourceMappingURL=babylon.webgl2.js.map
  6056. var BABYLON;
  6057. (function (BABYLON) {
  6058. var __decoratorInitialStore = {};
  6059. var __mergedStore = {};
  6060. var _copySource = function (creationFunction, source, instanciate) {
  6061. var destination = creationFunction();
  6062. // Tags
  6063. if (BABYLON.Tags) {
  6064. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6065. }
  6066. var classStore = getMergedStore(destination);
  6067. // Properties
  6068. for (var property in classStore) {
  6069. var propertyDescriptor = classStore[property];
  6070. var sourceProperty = source[property];
  6071. var propertyType = propertyDescriptor.type;
  6072. if (sourceProperty !== undefined && sourceProperty !== null) {
  6073. switch (propertyType) {
  6074. case 0: // Value
  6075. case 6:// Mesh reference
  6076. destination[property] = sourceProperty;
  6077. break;
  6078. case 1:// Texture
  6079. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6080. break;
  6081. case 2: // Color3
  6082. case 3: // FresnelParameters
  6083. case 4: // Vector2
  6084. case 5: // Vector3
  6085. case 7: // Color Curves
  6086. case 10:// Quaternion
  6087. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6088. break;
  6089. }
  6090. }
  6091. }
  6092. return destination;
  6093. };
  6094. function getDirectStore(target) {
  6095. var classKey = target.getClassName();
  6096. if (!__decoratorInitialStore[classKey]) {
  6097. __decoratorInitialStore[classKey] = {};
  6098. }
  6099. return __decoratorInitialStore[classKey];
  6100. }
  6101. /**
  6102. * Return the list of properties flagged as serializable
  6103. * @param target: host object
  6104. */
  6105. function getMergedStore(target) {
  6106. var classKey = target.getClassName();
  6107. if (__mergedStore[classKey]) {
  6108. return __mergedStore[classKey];
  6109. }
  6110. __mergedStore[classKey] = {};
  6111. var store = __mergedStore[classKey];
  6112. var currentTarget = target;
  6113. var currentKey = classKey;
  6114. while (currentKey) {
  6115. var initialStore = __decoratorInitialStore[currentKey];
  6116. for (var property in initialStore) {
  6117. store[property] = initialStore[property];
  6118. }
  6119. var parent_1 = void 0;
  6120. var done = false;
  6121. do {
  6122. parent_1 = Object.getPrototypeOf(currentTarget);
  6123. if (!parent_1.getClassName) {
  6124. done = true;
  6125. break;
  6126. }
  6127. if (parent_1.getClassName() !== currentKey) {
  6128. break;
  6129. }
  6130. currentTarget = parent_1;
  6131. } while (parent_1);
  6132. if (done) {
  6133. break;
  6134. }
  6135. currentKey = parent_1.getClassName();
  6136. currentTarget = parent_1;
  6137. }
  6138. return store;
  6139. }
  6140. function generateSerializableMember(type, sourceName) {
  6141. return function (target, propertyKey) {
  6142. var classStore = getDirectStore(target);
  6143. if (!classStore[propertyKey]) {
  6144. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6145. }
  6146. };
  6147. }
  6148. function generateExpandMember(setCallback, targetKey) {
  6149. if (targetKey === void 0) { targetKey = null; }
  6150. return function (target, propertyKey) {
  6151. var key = targetKey || ("_" + propertyKey);
  6152. Object.defineProperty(target, propertyKey, {
  6153. get: function () {
  6154. return this[key];
  6155. },
  6156. set: function (value) {
  6157. if (this[key] === value) {
  6158. return;
  6159. }
  6160. this[key] = value;
  6161. target[setCallback].apply(this);
  6162. },
  6163. enumerable: true,
  6164. configurable: true
  6165. });
  6166. };
  6167. }
  6168. function expandToProperty(callback, targetKey) {
  6169. if (targetKey === void 0) { targetKey = null; }
  6170. return generateExpandMember(callback, targetKey);
  6171. }
  6172. BABYLON.expandToProperty = expandToProperty;
  6173. function serialize(sourceName) {
  6174. return generateSerializableMember(0, sourceName); // value member
  6175. }
  6176. BABYLON.serialize = serialize;
  6177. function serializeAsTexture(sourceName) {
  6178. return generateSerializableMember(1, sourceName); // texture member
  6179. }
  6180. BABYLON.serializeAsTexture = serializeAsTexture;
  6181. function serializeAsColor3(sourceName) {
  6182. return generateSerializableMember(2, sourceName); // color3 member
  6183. }
  6184. BABYLON.serializeAsColor3 = serializeAsColor3;
  6185. function serializeAsFresnelParameters(sourceName) {
  6186. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6187. }
  6188. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6189. function serializeAsVector2(sourceName) {
  6190. return generateSerializableMember(4, sourceName); // vector2 member
  6191. }
  6192. BABYLON.serializeAsVector2 = serializeAsVector2;
  6193. function serializeAsVector3(sourceName) {
  6194. return generateSerializableMember(5, sourceName); // vector3 member
  6195. }
  6196. BABYLON.serializeAsVector3 = serializeAsVector3;
  6197. function serializeAsMeshReference(sourceName) {
  6198. return generateSerializableMember(6, sourceName); // mesh reference member
  6199. }
  6200. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6201. function serializeAsColorCurves(sourceName) {
  6202. return generateSerializableMember(7, sourceName); // color curves
  6203. }
  6204. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6205. function serializeAsColor4(sourceName) {
  6206. return generateSerializableMember(8, sourceName); // color 4
  6207. }
  6208. BABYLON.serializeAsColor4 = serializeAsColor4;
  6209. function serializeAsImageProcessingConfiguration(sourceName) {
  6210. return generateSerializableMember(9, sourceName); // image processing
  6211. }
  6212. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6213. function serializeAsQuaternion(sourceName) {
  6214. return generateSerializableMember(10, sourceName); // quaternion member
  6215. }
  6216. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6217. var SerializationHelper = /** @class */ (function () {
  6218. function SerializationHelper() {
  6219. }
  6220. SerializationHelper.Serialize = function (entity, serializationObject) {
  6221. if (!serializationObject) {
  6222. serializationObject = {};
  6223. }
  6224. // Tags
  6225. if (BABYLON.Tags) {
  6226. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6227. }
  6228. var serializedProperties = getMergedStore(entity);
  6229. // Properties
  6230. for (var property in serializedProperties) {
  6231. var propertyDescriptor = serializedProperties[property];
  6232. var targetPropertyName = propertyDescriptor.sourceName || property;
  6233. var propertyType = propertyDescriptor.type;
  6234. var sourceProperty = entity[property];
  6235. if (sourceProperty !== undefined && sourceProperty !== null) {
  6236. switch (propertyType) {
  6237. case 0:// Value
  6238. serializationObject[targetPropertyName] = sourceProperty;
  6239. break;
  6240. case 1:// Texture
  6241. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6242. break;
  6243. case 2:// Color3
  6244. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6245. break;
  6246. case 3:// FresnelParameters
  6247. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6248. break;
  6249. case 4:// Vector2
  6250. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6251. break;
  6252. case 5:// Vector3
  6253. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6254. break;
  6255. case 6:// Mesh reference
  6256. serializationObject[targetPropertyName] = sourceProperty.id;
  6257. break;
  6258. case 7:// Color Curves
  6259. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6260. break;
  6261. case 8:// Color 4
  6262. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6263. break;
  6264. case 9:// Image Processing
  6265. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6266. break;
  6267. }
  6268. }
  6269. }
  6270. return serializationObject;
  6271. };
  6272. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6273. if (rootUrl === void 0) { rootUrl = null; }
  6274. var destination = creationFunction();
  6275. if (!rootUrl) {
  6276. rootUrl = "";
  6277. }
  6278. // Tags
  6279. if (BABYLON.Tags) {
  6280. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6281. }
  6282. var classStore = getMergedStore(destination);
  6283. // Properties
  6284. for (var property in classStore) {
  6285. var propertyDescriptor = classStore[property];
  6286. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6287. var propertyType = propertyDescriptor.type;
  6288. if (sourceProperty !== undefined && sourceProperty !== null) {
  6289. var dest = destination;
  6290. switch (propertyType) {
  6291. case 0:// Value
  6292. dest[property] = sourceProperty;
  6293. break;
  6294. case 1:// Texture
  6295. if (scene) {
  6296. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6297. }
  6298. break;
  6299. case 2:// Color3
  6300. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6301. break;
  6302. case 3:// FresnelParameters
  6303. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6304. break;
  6305. case 4:// Vector2
  6306. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6307. break;
  6308. case 5:// Vector3
  6309. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6310. break;
  6311. case 6:// Mesh reference
  6312. if (scene) {
  6313. dest[property] = scene.getLastMeshByID(sourceProperty);
  6314. }
  6315. break;
  6316. case 7:// Color Curves
  6317. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6318. break;
  6319. case 8:// Color 4
  6320. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6321. break;
  6322. case 9:// Image Processing
  6323. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6324. break;
  6325. }
  6326. }
  6327. }
  6328. return destination;
  6329. };
  6330. SerializationHelper.Clone = function (creationFunction, source) {
  6331. return _copySource(creationFunction, source, false);
  6332. };
  6333. SerializationHelper.Instanciate = function (creationFunction, source) {
  6334. return _copySource(creationFunction, source, true);
  6335. };
  6336. return SerializationHelper;
  6337. }());
  6338. BABYLON.SerializationHelper = SerializationHelper;
  6339. })(BABYLON || (BABYLON = {}));
  6340. //# sourceMappingURL=babylon.decorators.js.map
  6341. var BABYLON;
  6342. (function (BABYLON) {
  6343. /**
  6344. * A class serves as a medium between the observable and its observers
  6345. */
  6346. var EventState = /** @class */ (function () {
  6347. /**
  6348. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6349. */
  6350. function EventState(mask, skipNextObservers, target, currentTarget) {
  6351. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6352. this.initalize(mask, skipNextObservers, target, currentTarget);
  6353. }
  6354. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6355. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6356. this.mask = mask;
  6357. this.skipNextObservers = skipNextObservers;
  6358. this.target = target;
  6359. this.currentTarget = currentTarget;
  6360. return this;
  6361. };
  6362. return EventState;
  6363. }());
  6364. BABYLON.EventState = EventState;
  6365. /**
  6366. * Represent an Observer registered to a given Observable object.
  6367. */
  6368. var Observer = /** @class */ (function () {
  6369. function Observer(callback, mask, scope) {
  6370. if (scope === void 0) { scope = null; }
  6371. this.callback = callback;
  6372. this.mask = mask;
  6373. this.scope = scope;
  6374. }
  6375. return Observer;
  6376. }());
  6377. BABYLON.Observer = Observer;
  6378. /**
  6379. * Represent a list of observers registered to multiple Observables object.
  6380. */
  6381. var MultiObserver = /** @class */ (function () {
  6382. function MultiObserver() {
  6383. }
  6384. MultiObserver.prototype.dispose = function () {
  6385. if (this._observers && this._observables) {
  6386. for (var index = 0; index < this._observers.length; index++) {
  6387. this._observables[index].remove(this._observers[index]);
  6388. }
  6389. }
  6390. this._observers = null;
  6391. this._observables = null;
  6392. };
  6393. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6394. if (mask === void 0) { mask = -1; }
  6395. if (scope === void 0) { scope = null; }
  6396. var result = new MultiObserver();
  6397. result._observers = new Array();
  6398. result._observables = observables;
  6399. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6400. var observable = observables_1[_i];
  6401. var observer = observable.add(callback, mask, false, scope);
  6402. if (observer) {
  6403. result._observers.push(observer);
  6404. }
  6405. }
  6406. return result;
  6407. };
  6408. return MultiObserver;
  6409. }());
  6410. BABYLON.MultiObserver = MultiObserver;
  6411. /**
  6412. * The Observable class is a simple implementation of the Observable pattern.
  6413. * 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.
  6414. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6415. * 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).
  6416. * 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.
  6417. */
  6418. var Observable = /** @class */ (function () {
  6419. function Observable(onObserverAdded) {
  6420. this._observers = new Array();
  6421. this._eventState = new EventState(0);
  6422. if (onObserverAdded) {
  6423. this._onObserverAdded = onObserverAdded;
  6424. }
  6425. }
  6426. /**
  6427. * Create a new Observer with the specified callback
  6428. * @param callback the callback that will be executed for that Observer
  6429. * @param mask the mask used to filter observers
  6430. * @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.
  6431. * @param scope optional scope for the callback to be called from
  6432. */
  6433. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6434. if (mask === void 0) { mask = -1; }
  6435. if (insertFirst === void 0) { insertFirst = false; }
  6436. if (scope === void 0) { scope = null; }
  6437. if (!callback) {
  6438. return null;
  6439. }
  6440. var observer = new Observer(callback, mask, scope);
  6441. if (insertFirst) {
  6442. this._observers.unshift(observer);
  6443. }
  6444. else {
  6445. this._observers.push(observer);
  6446. }
  6447. if (this._onObserverAdded) {
  6448. this._onObserverAdded(observer);
  6449. }
  6450. return observer;
  6451. };
  6452. /**
  6453. * Remove an Observer from the Observable object
  6454. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6455. */
  6456. Observable.prototype.remove = function (observer) {
  6457. if (!observer) {
  6458. return false;
  6459. }
  6460. var index = this._observers.indexOf(observer);
  6461. if (index !== -1) {
  6462. this._observers.splice(index, 1);
  6463. return true;
  6464. }
  6465. return false;
  6466. };
  6467. /**
  6468. * Remove a callback from the Observable object
  6469. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6470. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6471. */
  6472. Observable.prototype.removeCallback = function (callback, scope) {
  6473. for (var index = 0; index < this._observers.length; index++) {
  6474. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6475. this._observers.splice(index, 1);
  6476. return true;
  6477. }
  6478. }
  6479. return false;
  6480. };
  6481. /**
  6482. * Notify all Observers by calling their respective callback with the given data
  6483. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6484. * @param eventData
  6485. * @param mask
  6486. */
  6487. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6488. if (mask === void 0) { mask = -1; }
  6489. if (!this._observers.length) {
  6490. return true;
  6491. }
  6492. var state = this._eventState;
  6493. state.mask = mask;
  6494. state.target = target;
  6495. state.currentTarget = currentTarget;
  6496. state.skipNextObservers = false;
  6497. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6498. var obs = _a[_i];
  6499. if (obs.mask & mask) {
  6500. if (obs.scope) {
  6501. obs.callback.apply(obs.scope, [eventData, state]);
  6502. }
  6503. else {
  6504. obs.callback(eventData, state);
  6505. }
  6506. }
  6507. if (state.skipNextObservers) {
  6508. return false;
  6509. }
  6510. }
  6511. return true;
  6512. };
  6513. /**
  6514. * Notify a specific observer
  6515. * @param eventData
  6516. * @param mask
  6517. */
  6518. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6519. if (mask === void 0) { mask = -1; }
  6520. var state = this._eventState;
  6521. state.mask = mask;
  6522. state.skipNextObservers = false;
  6523. observer.callback(eventData, state);
  6524. };
  6525. /**
  6526. * return true is the Observable has at least one Observer registered
  6527. */
  6528. Observable.prototype.hasObservers = function () {
  6529. return this._observers.length > 0;
  6530. };
  6531. /**
  6532. * Clear the list of observers
  6533. */
  6534. Observable.prototype.clear = function () {
  6535. this._observers = new Array();
  6536. this._onObserverAdded = null;
  6537. };
  6538. /**
  6539. * Clone the current observable
  6540. */
  6541. Observable.prototype.clone = function () {
  6542. var result = new Observable();
  6543. result._observers = this._observers.slice(0);
  6544. return result;
  6545. };
  6546. /**
  6547. * Does this observable handles observer registered with a given mask
  6548. * @param {number} trigger - the mask to be tested
  6549. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6550. **/
  6551. Observable.prototype.hasSpecificMask = function (mask) {
  6552. if (mask === void 0) { mask = -1; }
  6553. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6554. var obs = _a[_i];
  6555. if (obs.mask & mask || obs.mask === mask) {
  6556. return true;
  6557. }
  6558. }
  6559. return false;
  6560. };
  6561. return Observable;
  6562. }());
  6563. BABYLON.Observable = Observable;
  6564. })(BABYLON || (BABYLON = {}));
  6565. //# sourceMappingURL=babylon.observable.js.map
  6566. var BABYLON;
  6567. (function (BABYLON) {
  6568. var SmartArray = /** @class */ (function () {
  6569. function SmartArray(capacity) {
  6570. this.length = 0;
  6571. this.data = new Array(capacity);
  6572. this._id = SmartArray._GlobalId++;
  6573. }
  6574. SmartArray.prototype.push = function (value) {
  6575. this.data[this.length++] = value;
  6576. if (this.length > this.data.length) {
  6577. this.data.length *= 2;
  6578. }
  6579. };
  6580. SmartArray.prototype.forEach = function (func) {
  6581. for (var index = 0; index < this.length; index++) {
  6582. func(this.data[index]);
  6583. }
  6584. };
  6585. SmartArray.prototype.sort = function (compareFn) {
  6586. this.data.sort(compareFn);
  6587. };
  6588. SmartArray.prototype.reset = function () {
  6589. this.length = 0;
  6590. };
  6591. SmartArray.prototype.dispose = function () {
  6592. this.reset();
  6593. if (this.data) {
  6594. this.data.length = 0;
  6595. this.data = [];
  6596. }
  6597. };
  6598. SmartArray.prototype.concat = function (array) {
  6599. if (array.length === 0) {
  6600. return;
  6601. }
  6602. if (this.length + array.length > this.data.length) {
  6603. this.data.length = (this.length + array.length) * 2;
  6604. }
  6605. for (var index = 0; index < array.length; index++) {
  6606. this.data[this.length++] = (array.data || array)[index];
  6607. }
  6608. };
  6609. SmartArray.prototype.indexOf = function (value) {
  6610. var position = this.data.indexOf(value);
  6611. if (position >= this.length) {
  6612. return -1;
  6613. }
  6614. return position;
  6615. };
  6616. SmartArray.prototype.contains = function (value) {
  6617. return this.data.indexOf(value) !== -1;
  6618. };
  6619. // Statics
  6620. SmartArray._GlobalId = 0;
  6621. return SmartArray;
  6622. }());
  6623. BABYLON.SmartArray = SmartArray;
  6624. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6625. __extends(SmartArrayNoDuplicate, _super);
  6626. function SmartArrayNoDuplicate() {
  6627. var _this = _super !== null && _super.apply(this, arguments) || this;
  6628. _this._duplicateId = 0;
  6629. return _this;
  6630. }
  6631. SmartArrayNoDuplicate.prototype.push = function (value) {
  6632. _super.prototype.push.call(this, value);
  6633. if (!value.__smartArrayFlags) {
  6634. value.__smartArrayFlags = {};
  6635. }
  6636. value.__smartArrayFlags[this._id] = this._duplicateId;
  6637. };
  6638. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6639. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6640. return false;
  6641. }
  6642. this.push(value);
  6643. return true;
  6644. };
  6645. SmartArrayNoDuplicate.prototype.reset = function () {
  6646. _super.prototype.reset.call(this);
  6647. this._duplicateId++;
  6648. };
  6649. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6650. if (array.length === 0) {
  6651. return;
  6652. }
  6653. if (this.length + array.length > this.data.length) {
  6654. this.data.length = (this.length + array.length) * 2;
  6655. }
  6656. for (var index = 0; index < array.length; index++) {
  6657. var item = (array.data || array)[index];
  6658. this.pushNoDuplicate(item);
  6659. }
  6660. };
  6661. return SmartArrayNoDuplicate;
  6662. }(SmartArray));
  6663. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6664. })(BABYLON || (BABYLON = {}));
  6665. //# sourceMappingURL=babylon.smartArray.js.map
  6666. var BABYLON;
  6667. (function (BABYLON) {
  6668. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6669. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6670. var LoadFileError = /** @class */ (function (_super) {
  6671. __extends(LoadFileError, _super);
  6672. function LoadFileError(message, request) {
  6673. var _this = _super.call(this, message) || this;
  6674. _this.request = request;
  6675. _this.name = "LoadFileError";
  6676. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6677. return _this;
  6678. }
  6679. // Polyfill for Object.setPrototypeOf if necessary.
  6680. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6681. return LoadFileError;
  6682. }(Error));
  6683. BABYLON.LoadFileError = LoadFileError;
  6684. var RetryStrategy = /** @class */ (function () {
  6685. function RetryStrategy() {
  6686. }
  6687. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6688. if (maxRetries === void 0) { maxRetries = 3; }
  6689. if (baseInterval === void 0) { baseInterval = 500; }
  6690. return function (url, request, retryIndex) {
  6691. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6692. return -1;
  6693. }
  6694. return Math.pow(2, retryIndex) * baseInterval;
  6695. };
  6696. };
  6697. return RetryStrategy;
  6698. }());
  6699. BABYLON.RetryStrategy = RetryStrategy;
  6700. // Screenshots
  6701. var screenshotCanvas;
  6702. var cloneValue = function (source, destinationObject) {
  6703. if (!source)
  6704. return null;
  6705. if (source instanceof BABYLON.Mesh) {
  6706. return null;
  6707. }
  6708. if (source instanceof BABYLON.SubMesh) {
  6709. return source.clone(destinationObject);
  6710. }
  6711. else if (source.clone) {
  6712. return source.clone();
  6713. }
  6714. return null;
  6715. };
  6716. var Tools = /** @class */ (function () {
  6717. function Tools() {
  6718. }
  6719. /**
  6720. * Interpolates between a and b via alpha
  6721. * @param a The lower value (returned when alpha = 0)
  6722. * @param b The upper value (returned when alpha = 1)
  6723. * @param alpha The interpolation-factor
  6724. * @return The mixed value
  6725. */
  6726. Tools.Mix = function (a, b, alpha) {
  6727. return a * (1 - alpha) + b * alpha;
  6728. };
  6729. Tools.Instantiate = function (className) {
  6730. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6731. return Tools.RegisteredExternalClasses[className];
  6732. }
  6733. var arr = className.split(".");
  6734. var fn = (window || this);
  6735. for (var i = 0, len = arr.length; i < len; i++) {
  6736. fn = fn[arr[i]];
  6737. }
  6738. if (typeof fn !== "function") {
  6739. return null;
  6740. }
  6741. return fn;
  6742. };
  6743. /**
  6744. * Provides a slice function that will work even on IE
  6745. * @param data defines the array to slice
  6746. * @returns the new sliced array
  6747. */
  6748. Tools.Slice = function (data) {
  6749. if (data.slice) {
  6750. return data.slice();
  6751. }
  6752. return Array.prototype.slice.call(data);
  6753. };
  6754. Tools.SetImmediate = function (action) {
  6755. if (window.setImmediate) {
  6756. window.setImmediate(action);
  6757. }
  6758. else {
  6759. setTimeout(action, 1);
  6760. }
  6761. };
  6762. Tools.IsExponentOfTwo = function (value) {
  6763. var count = 1;
  6764. do {
  6765. count *= 2;
  6766. } while (count < value);
  6767. return count === value;
  6768. };
  6769. /**
  6770. * Find the next highest power of two.
  6771. * @param x Number to start search from.
  6772. * @return Next highest power of two.
  6773. */
  6774. Tools.CeilingPOT = function (x) {
  6775. x--;
  6776. x |= x >> 1;
  6777. x |= x >> 2;
  6778. x |= x >> 4;
  6779. x |= x >> 8;
  6780. x |= x >> 16;
  6781. x++;
  6782. return x;
  6783. };
  6784. /**
  6785. * Find the next lowest power of two.
  6786. * @param x Number to start search from.
  6787. * @return Next lowest power of two.
  6788. */
  6789. Tools.FloorPOT = function (x) {
  6790. x = x | (x >> 1);
  6791. x = x | (x >> 2);
  6792. x = x | (x >> 4);
  6793. x = x | (x >> 8);
  6794. x = x | (x >> 16);
  6795. return x - (x >> 1);
  6796. };
  6797. /**
  6798. * Find the nearest power of two.
  6799. * @param x Number to start search from.
  6800. * @return Next nearest power of two.
  6801. */
  6802. Tools.NearestPOT = function (x) {
  6803. var c = Tools.CeilingPOT(x);
  6804. var f = Tools.FloorPOT(x);
  6805. return (c - x) > (x - f) ? f : c;
  6806. };
  6807. Tools.GetExponentOfTwo = function (value, max, mode) {
  6808. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6809. var pot;
  6810. switch (mode) {
  6811. case BABYLON.Engine.SCALEMODE_FLOOR:
  6812. pot = Tools.FloorPOT(value);
  6813. break;
  6814. case BABYLON.Engine.SCALEMODE_NEAREST:
  6815. pot = Tools.NearestPOT(value);
  6816. break;
  6817. case BABYLON.Engine.SCALEMODE_CEILING:
  6818. default:
  6819. pot = Tools.CeilingPOT(value);
  6820. break;
  6821. }
  6822. return Math.min(pot, max);
  6823. };
  6824. Tools.GetFilename = function (path) {
  6825. var index = path.lastIndexOf("/");
  6826. if (index < 0)
  6827. return path;
  6828. return path.substring(index + 1);
  6829. };
  6830. Tools.GetFolderPath = function (uri) {
  6831. var index = uri.lastIndexOf("/");
  6832. if (index < 0)
  6833. return "";
  6834. return uri.substring(0, index + 1);
  6835. };
  6836. Tools.GetDOMTextContent = function (element) {
  6837. var result = "";
  6838. var child = element.firstChild;
  6839. while (child) {
  6840. if (child.nodeType === 3) {
  6841. result += child.textContent;
  6842. }
  6843. child = child.nextSibling;
  6844. }
  6845. return result;
  6846. };
  6847. Tools.ToDegrees = function (angle) {
  6848. return angle * 180 / Math.PI;
  6849. };
  6850. Tools.ToRadians = function (angle) {
  6851. return angle * Math.PI / 180;
  6852. };
  6853. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6854. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6855. var output = "";
  6856. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6857. var i = 0;
  6858. var bytes = new Uint8Array(buffer);
  6859. while (i < bytes.length) {
  6860. chr1 = bytes[i++];
  6861. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6862. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6863. enc1 = chr1 >> 2;
  6864. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6865. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6866. enc4 = chr3 & 63;
  6867. if (isNaN(chr2)) {
  6868. enc3 = enc4 = 64;
  6869. }
  6870. else if (isNaN(chr3)) {
  6871. enc4 = 64;
  6872. }
  6873. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6874. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6875. }
  6876. return "data:image/png;base64," + output;
  6877. };
  6878. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6879. if (bias === void 0) { bias = null; }
  6880. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6881. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6882. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6883. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6884. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6885. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6886. }
  6887. if (bias) {
  6888. minimum.x -= minimum.x * bias.x + bias.y;
  6889. minimum.y -= minimum.y * bias.x + bias.y;
  6890. minimum.z -= minimum.z * bias.x + bias.y;
  6891. maximum.x += maximum.x * bias.x + bias.y;
  6892. maximum.y += maximum.y * bias.x + bias.y;
  6893. maximum.z += maximum.z * bias.x + bias.y;
  6894. }
  6895. return {
  6896. minimum: minimum,
  6897. maximum: maximum
  6898. };
  6899. };
  6900. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6901. if (bias === void 0) { bias = null; }
  6902. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6903. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6904. if (!stride) {
  6905. stride = 3;
  6906. }
  6907. for (var index = start; index < start + count; index++) {
  6908. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6909. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6910. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6911. }
  6912. if (bias) {
  6913. minimum.x -= minimum.x * bias.x + bias.y;
  6914. minimum.y -= minimum.y * bias.x + bias.y;
  6915. minimum.z -= minimum.z * bias.x + bias.y;
  6916. maximum.x += maximum.x * bias.x + bias.y;
  6917. maximum.y += maximum.y * bias.x + bias.y;
  6918. maximum.z += maximum.z * bias.x + bias.y;
  6919. }
  6920. return {
  6921. minimum: minimum,
  6922. maximum: maximum
  6923. };
  6924. };
  6925. Tools.Vector2ArrayFeeder = function (array) {
  6926. return function (index) {
  6927. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6928. var length = isFloatArray ? array.length / 2 : array.length;
  6929. if (index >= length) {
  6930. return null;
  6931. }
  6932. if (isFloatArray) {
  6933. var fa = array;
  6934. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6935. }
  6936. var a = array;
  6937. return a[index];
  6938. };
  6939. };
  6940. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6941. if (bias === void 0) { bias = null; }
  6942. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6943. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6944. var i = 0;
  6945. var cur = feeder(i++);
  6946. while (cur) {
  6947. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6948. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6949. cur = feeder(i++);
  6950. }
  6951. if (bias) {
  6952. minimum.x -= minimum.x * bias.x + bias.y;
  6953. minimum.y -= minimum.y * bias.x + bias.y;
  6954. maximum.x += maximum.x * bias.x + bias.y;
  6955. maximum.y += maximum.y * bias.x + bias.y;
  6956. }
  6957. return {
  6958. minimum: minimum,
  6959. maximum: maximum
  6960. };
  6961. };
  6962. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6963. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6964. return null;
  6965. return Array.isArray(obj) ? obj : [obj];
  6966. };
  6967. // Misc.
  6968. Tools.GetPointerPrefix = function () {
  6969. var eventPrefix = "pointer";
  6970. // Check if pointer events are supported
  6971. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6972. eventPrefix = "mouse";
  6973. }
  6974. return eventPrefix;
  6975. };
  6976. /**
  6977. * @param func - the function to be called
  6978. * @param requester - the object that will request the next frame. Falls back to window.
  6979. */
  6980. Tools.QueueNewFrame = function (func, requester) {
  6981. if (!Tools.IsWindowObjectExist()) {
  6982. return setTimeout(func, 16);
  6983. }
  6984. if (!requester) {
  6985. requester = window;
  6986. }
  6987. if (requester.requestAnimationFrame) {
  6988. return requester.requestAnimationFrame(func);
  6989. }
  6990. else if (requester.msRequestAnimationFrame) {
  6991. return requester.msRequestAnimationFrame(func);
  6992. }
  6993. else if (requester.webkitRequestAnimationFrame) {
  6994. return requester.webkitRequestAnimationFrame(func);
  6995. }
  6996. else if (requester.mozRequestAnimationFrame) {
  6997. return requester.mozRequestAnimationFrame(func);
  6998. }
  6999. else if (requester.oRequestAnimationFrame) {
  7000. return requester.oRequestAnimationFrame(func);
  7001. }
  7002. else {
  7003. return window.setTimeout(func, 16);
  7004. }
  7005. };
  7006. Tools.RequestFullscreen = function (element) {
  7007. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7008. if (!requestFunction)
  7009. return;
  7010. requestFunction.call(element);
  7011. };
  7012. Tools.ExitFullscreen = function () {
  7013. if (document.exitFullscreen) {
  7014. document.exitFullscreen();
  7015. }
  7016. else if (document.mozCancelFullScreen) {
  7017. document.mozCancelFullScreen();
  7018. }
  7019. else if (document.webkitCancelFullScreen) {
  7020. document.webkitCancelFullScreen();
  7021. }
  7022. else if (document.msCancelFullScreen) {
  7023. document.msCancelFullScreen();
  7024. }
  7025. };
  7026. Tools.SetCorsBehavior = function (url, element) {
  7027. if (url && url.indexOf("data:") === 0) {
  7028. return;
  7029. }
  7030. if (Tools.CorsBehavior) {
  7031. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7032. element.crossOrigin = Tools.CorsBehavior;
  7033. }
  7034. else {
  7035. var result = Tools.CorsBehavior(url);
  7036. if (result) {
  7037. element.crossOrigin = result;
  7038. }
  7039. }
  7040. }
  7041. };
  7042. // External files
  7043. Tools.CleanUrl = function (url) {
  7044. url = url.replace(/#/mg, "%23");
  7045. return url;
  7046. };
  7047. Tools.LoadImage = function (url, onLoad, onError, database) {
  7048. if (url instanceof ArrayBuffer) {
  7049. url = Tools.EncodeArrayBufferTobase64(url);
  7050. }
  7051. url = Tools.CleanUrl(url);
  7052. url = Tools.PreprocessUrl(url);
  7053. var img = new Image();
  7054. Tools.SetCorsBehavior(url, img);
  7055. img.onload = function () {
  7056. onLoad(img);
  7057. };
  7058. img.onerror = function (err) {
  7059. Tools.Error("Error while trying to load image: " + url);
  7060. if (onError) {
  7061. onError("Error while trying to load image: " + url, err);
  7062. }
  7063. };
  7064. var noIndexedDB = function () {
  7065. img.src = url;
  7066. };
  7067. var loadFromIndexedDB = function () {
  7068. if (database) {
  7069. database.loadImageFromDB(url, img);
  7070. }
  7071. };
  7072. //ANY database to do!
  7073. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7074. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7075. }
  7076. else {
  7077. if (url.indexOf("file:") !== -1) {
  7078. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7079. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7080. try {
  7081. var blobURL;
  7082. try {
  7083. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7084. }
  7085. catch (ex) {
  7086. // Chrome doesn't support oneTimeOnly parameter
  7087. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7088. }
  7089. img.src = blobURL;
  7090. }
  7091. catch (e) {
  7092. img.src = "";
  7093. }
  7094. return img;
  7095. }
  7096. }
  7097. noIndexedDB();
  7098. }
  7099. return img;
  7100. };
  7101. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7102. url = Tools.CleanUrl(url);
  7103. url = Tools.PreprocessUrl(url);
  7104. // If file and file input are set
  7105. if (url.indexOf("file:") !== -1) {
  7106. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7107. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7108. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7109. }
  7110. }
  7111. var loadUrl = Tools.BaseUrl + url;
  7112. var aborted = false;
  7113. var fileRequest = {
  7114. onCompleteObservable: new BABYLON.Observable(),
  7115. abort: function () { return aborted = true; },
  7116. };
  7117. var requestFile = function () {
  7118. var request = new XMLHttpRequest();
  7119. var retryHandle = null;
  7120. fileRequest.abort = function () {
  7121. aborted = true;
  7122. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7123. request.abort();
  7124. }
  7125. if (retryHandle !== null) {
  7126. clearTimeout(retryHandle);
  7127. retryHandle = null;
  7128. }
  7129. };
  7130. var retryLoop = function (retryIndex) {
  7131. request.open('GET', loadUrl, true);
  7132. if (useArrayBuffer) {
  7133. request.responseType = "arraybuffer";
  7134. }
  7135. if (onProgress) {
  7136. request.addEventListener("progress", onProgress);
  7137. }
  7138. var onLoadEnd = function () {
  7139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7140. };
  7141. request.addEventListener("loadend", onLoadEnd);
  7142. var onReadyStateChange = function () {
  7143. if (aborted) {
  7144. return;
  7145. }
  7146. // In case of undefined state in some browsers.
  7147. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7148. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7149. request.removeEventListener("readystatechange", onReadyStateChange);
  7150. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7151. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7152. return;
  7153. }
  7154. var retryStrategy = Tools.DefaultRetryStrategy;
  7155. if (retryStrategy) {
  7156. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7157. if (waitTime !== -1) {
  7158. // Prevent the request from completing for retry.
  7159. request.removeEventListener("loadend", onLoadEnd);
  7160. request = new XMLHttpRequest();
  7161. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7162. return;
  7163. }
  7164. }
  7165. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7166. if (onError) {
  7167. onError(request, e);
  7168. }
  7169. else {
  7170. throw e;
  7171. }
  7172. }
  7173. };
  7174. request.addEventListener("readystatechange", onReadyStateChange);
  7175. request.send();
  7176. };
  7177. retryLoop(0);
  7178. };
  7179. // Caching all files
  7180. if (database && database.enableSceneOffline) {
  7181. var noIndexedDB_1 = function () {
  7182. if (!aborted) {
  7183. requestFile();
  7184. }
  7185. };
  7186. var loadFromIndexedDB = function () {
  7187. // TODO: database needs to support aborting and should return a IFileRequest
  7188. if (aborted) {
  7189. return;
  7190. }
  7191. if (database) {
  7192. database.loadFileFromDB(url, function (data) {
  7193. if (!aborted) {
  7194. onSuccess(data);
  7195. }
  7196. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7197. }, onProgress ? function (event) {
  7198. if (!aborted) {
  7199. onProgress(event);
  7200. }
  7201. } : undefined, noIndexedDB_1, useArrayBuffer);
  7202. }
  7203. };
  7204. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7205. }
  7206. else {
  7207. requestFile();
  7208. }
  7209. return fileRequest;
  7210. };
  7211. /**
  7212. * Load a script (identified by an url). When the url returns, the
  7213. * content of this file is added into a new script element, attached to the DOM (body element)
  7214. */
  7215. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7216. var head = document.getElementsByTagName('head')[0];
  7217. var script = document.createElement('script');
  7218. script.type = 'text/javascript';
  7219. script.src = scriptUrl;
  7220. script.onload = function () {
  7221. if (onSuccess) {
  7222. onSuccess();
  7223. }
  7224. };
  7225. script.onerror = function (e) {
  7226. if (onError) {
  7227. onError("Unable to load script", e);
  7228. }
  7229. };
  7230. head.appendChild(script);
  7231. };
  7232. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7233. var reader = new FileReader();
  7234. var request = {
  7235. onCompleteObservable: new BABYLON.Observable(),
  7236. abort: function () { return reader.abort(); },
  7237. };
  7238. reader.onloadend = function (e) {
  7239. request.onCompleteObservable.notifyObservers(request);
  7240. };
  7241. reader.onload = function (e) {
  7242. //target doesn't have result from ts 1.3
  7243. callback(e.target['result']);
  7244. };
  7245. reader.onprogress = progressCallback;
  7246. reader.readAsDataURL(fileToLoad);
  7247. return request;
  7248. };
  7249. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7250. var reader = new FileReader();
  7251. var request = {
  7252. onCompleteObservable: new BABYLON.Observable(),
  7253. abort: function () { return reader.abort(); },
  7254. };
  7255. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7256. reader.onerror = function (e) {
  7257. Tools.Log("Error while reading file: " + fileToLoad.name);
  7258. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7259. };
  7260. reader.onload = function (e) {
  7261. //target doesn't have result from ts 1.3
  7262. callback(e.target['result']);
  7263. };
  7264. if (progressCallBack) {
  7265. reader.onprogress = progressCallBack;
  7266. }
  7267. if (!useArrayBuffer) {
  7268. // Asynchronous read
  7269. reader.readAsText(fileToLoad);
  7270. }
  7271. else {
  7272. reader.readAsArrayBuffer(fileToLoad);
  7273. }
  7274. return request;
  7275. };
  7276. //returns a downloadable url to a file content.
  7277. Tools.FileAsURL = function (content) {
  7278. var fileBlob = new Blob([content]);
  7279. var url = window.URL || window.webkitURL;
  7280. var link = url.createObjectURL(fileBlob);
  7281. return link;
  7282. };
  7283. // Misc.
  7284. Tools.Format = function (value, decimals) {
  7285. if (decimals === void 0) { decimals = 2; }
  7286. return value.toFixed(decimals);
  7287. };
  7288. Tools.CheckExtends = function (v, min, max) {
  7289. if (v.x < min.x)
  7290. min.x = v.x;
  7291. if (v.y < min.y)
  7292. min.y = v.y;
  7293. if (v.z < min.z)
  7294. min.z = v.z;
  7295. if (v.x > max.x)
  7296. max.x = v.x;
  7297. if (v.y > max.y)
  7298. max.y = v.y;
  7299. if (v.z > max.z)
  7300. max.z = v.z;
  7301. };
  7302. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7303. for (var prop in source) {
  7304. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7305. continue;
  7306. }
  7307. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7308. continue;
  7309. }
  7310. var sourceValue = source[prop];
  7311. var typeOfSourceValue = typeof sourceValue;
  7312. if (typeOfSourceValue === "function") {
  7313. continue;
  7314. }
  7315. if (typeOfSourceValue === "object") {
  7316. if (sourceValue instanceof Array) {
  7317. destination[prop] = [];
  7318. if (sourceValue.length > 0) {
  7319. if (typeof sourceValue[0] == "object") {
  7320. for (var index = 0; index < sourceValue.length; index++) {
  7321. var clonedValue = cloneValue(sourceValue[index], destination);
  7322. if (destination[prop].indexOf(clonedValue) === -1) {
  7323. destination[prop].push(clonedValue);
  7324. }
  7325. }
  7326. }
  7327. else {
  7328. destination[prop] = sourceValue.slice(0);
  7329. }
  7330. }
  7331. }
  7332. else {
  7333. destination[prop] = cloneValue(sourceValue, destination);
  7334. }
  7335. }
  7336. else {
  7337. destination[prop] = sourceValue;
  7338. }
  7339. }
  7340. };
  7341. Tools.IsEmpty = function (obj) {
  7342. for (var i in obj) {
  7343. if (obj.hasOwnProperty(i)) {
  7344. return false;
  7345. }
  7346. }
  7347. return true;
  7348. };
  7349. Tools.RegisterTopRootEvents = function (events) {
  7350. for (var index = 0; index < events.length; index++) {
  7351. var event = events[index];
  7352. window.addEventListener(event.name, event.handler, false);
  7353. try {
  7354. if (window.parent) {
  7355. window.parent.addEventListener(event.name, event.handler, false);
  7356. }
  7357. }
  7358. catch (e) {
  7359. // Silently fails...
  7360. }
  7361. }
  7362. };
  7363. Tools.UnregisterTopRootEvents = function (events) {
  7364. for (var index = 0; index < events.length; index++) {
  7365. var event = events[index];
  7366. window.removeEventListener(event.name, event.handler);
  7367. try {
  7368. if (window.parent) {
  7369. window.parent.removeEventListener(event.name, event.handler);
  7370. }
  7371. }
  7372. catch (e) {
  7373. // Silently fails...
  7374. }
  7375. }
  7376. };
  7377. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7378. if (mimeType === void 0) { mimeType = "image/png"; }
  7379. // Read the contents of the framebuffer
  7380. var numberOfChannelsByLine = width * 4;
  7381. var halfHeight = height / 2;
  7382. //Reading datas from WebGL
  7383. var data = engine.readPixels(0, 0, width, height);
  7384. //To flip image on Y axis.
  7385. for (var i = 0; i < halfHeight; i++) {
  7386. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7387. var currentCell = j + i * numberOfChannelsByLine;
  7388. var targetLine = height - i - 1;
  7389. var targetCell = j + targetLine * numberOfChannelsByLine;
  7390. var temp = data[currentCell];
  7391. data[currentCell] = data[targetCell];
  7392. data[targetCell] = temp;
  7393. }
  7394. }
  7395. // Create a 2D canvas to store the result
  7396. if (!screenshotCanvas) {
  7397. screenshotCanvas = document.createElement('canvas');
  7398. }
  7399. screenshotCanvas.width = width;
  7400. screenshotCanvas.height = height;
  7401. var context = screenshotCanvas.getContext('2d');
  7402. if (context) {
  7403. // Copy the pixels to a 2D canvas
  7404. var imageData = context.createImageData(width, height);
  7405. var castData = (imageData.data);
  7406. castData.set(data);
  7407. context.putImageData(imageData, 0, 0);
  7408. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7409. }
  7410. };
  7411. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7412. if (mimeType === void 0) { mimeType = "image/png"; }
  7413. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7414. if (successCallback) {
  7415. successCallback(base64Image);
  7416. }
  7417. else {
  7418. // We need HTMLCanvasElement.toBlob for HD screenshots
  7419. if (!screenshotCanvas.toBlob) {
  7420. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7421. screenshotCanvas.toBlob = function (callback, type, quality) {
  7422. var _this = this;
  7423. setTimeout(function () {
  7424. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7425. for (var i = 0; i < len; i++) {
  7426. arr[i] = binStr.charCodeAt(i);
  7427. }
  7428. callback(new Blob([arr], { type: type || 'image/png' }));
  7429. });
  7430. };
  7431. }
  7432. screenshotCanvas.toBlob(function (blob) {
  7433. var url = URL.createObjectURL(blob);
  7434. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7435. if (("download" in document.createElement("a"))) {
  7436. var a = window.document.createElement("a");
  7437. a.href = url;
  7438. if (fileName) {
  7439. a.setAttribute("download", fileName);
  7440. }
  7441. else {
  7442. var date = new Date();
  7443. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7444. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7445. }
  7446. window.document.body.appendChild(a);
  7447. a.addEventListener("click", function () {
  7448. if (a.parentElement) {
  7449. a.parentElement.removeChild(a);
  7450. }
  7451. });
  7452. a.click();
  7453. }
  7454. else {
  7455. var newWindow = window.open("");
  7456. if (!newWindow)
  7457. return;
  7458. var img = newWindow.document.createElement("img");
  7459. img.onload = function () {
  7460. // no longer need to read the blob so it's revoked
  7461. URL.revokeObjectURL(url);
  7462. };
  7463. img.src = url;
  7464. newWindow.document.body.appendChild(img);
  7465. }
  7466. });
  7467. }
  7468. };
  7469. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7470. if (mimeType === void 0) { mimeType = "image/png"; }
  7471. var width;
  7472. var height;
  7473. // If a precision value is specified
  7474. if (size.precision) {
  7475. width = Math.round(engine.getRenderWidth() * size.precision);
  7476. height = Math.round(width / engine.getAspectRatio(camera));
  7477. }
  7478. else if (size.width && size.height) {
  7479. width = size.width;
  7480. height = size.height;
  7481. }
  7482. else if (size.width && !size.height) {
  7483. width = size.width;
  7484. height = Math.round(width / engine.getAspectRatio(camera));
  7485. }
  7486. else if (size.height && !size.width) {
  7487. height = size.height;
  7488. width = Math.round(height * engine.getAspectRatio(camera));
  7489. }
  7490. else if (!isNaN(size)) {
  7491. height = size;
  7492. width = size;
  7493. }
  7494. else {
  7495. Tools.Error("Invalid 'size' parameter !");
  7496. return;
  7497. }
  7498. if (!screenshotCanvas) {
  7499. screenshotCanvas = document.createElement('canvas');
  7500. }
  7501. screenshotCanvas.width = width;
  7502. screenshotCanvas.height = height;
  7503. var renderContext = screenshotCanvas.getContext("2d");
  7504. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7505. var newWidth = width;
  7506. var newHeight = newWidth / ratio;
  7507. if (newHeight > height) {
  7508. newHeight = height;
  7509. newWidth = newHeight * ratio;
  7510. }
  7511. var offsetX = Math.max(0, width - newWidth) / 2;
  7512. var offsetY = Math.max(0, height - newHeight) / 2;
  7513. var renderingCanvas = engine.getRenderingCanvas();
  7514. if (renderContext && renderingCanvas) {
  7515. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7516. }
  7517. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7518. };
  7519. /**
  7520. * Generates an image screenshot from the specified camera.
  7521. *
  7522. * @param engine The engine to use for rendering
  7523. * @param camera The camera to use for rendering
  7524. * @param size This parameter can be set to a single number or to an object with the
  7525. * following (optional) properties: precision, width, height. If a single number is passed,
  7526. * it will be used for both width and height. If an object is passed, the screenshot size
  7527. * will be derived from the parameters. The precision property is a multiplier allowing
  7528. * rendering at a higher or lower resolution.
  7529. * @param successCallback The callback receives a single parameter which contains the
  7530. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7531. * src parameter of an <img> to display it.
  7532. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7533. * Check your browser for supported MIME types.
  7534. * @param samples Texture samples (default: 1)
  7535. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7536. * @param fileName A name for for the downloaded file.
  7537. * @constructor
  7538. */
  7539. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7540. if (mimeType === void 0) { mimeType = "image/png"; }
  7541. if (samples === void 0) { samples = 1; }
  7542. if (antialiasing === void 0) { antialiasing = false; }
  7543. var width;
  7544. var height;
  7545. //If a precision value is specified
  7546. if (size.precision) {
  7547. width = Math.round(engine.getRenderWidth() * size.precision);
  7548. height = Math.round(width / engine.getAspectRatio(camera));
  7549. size = { width: width, height: height };
  7550. }
  7551. else if (size.width && size.height) {
  7552. width = size.width;
  7553. height = size.height;
  7554. }
  7555. else if (size.width && !size.height) {
  7556. width = size.width;
  7557. height = Math.round(width / engine.getAspectRatio(camera));
  7558. size = { width: width, height: height };
  7559. }
  7560. else if (size.height && !size.width) {
  7561. height = size.height;
  7562. width = Math.round(height * engine.getAspectRatio(camera));
  7563. size = { width: width, height: height };
  7564. }
  7565. else if (!isNaN(size)) {
  7566. height = size;
  7567. width = size;
  7568. }
  7569. else {
  7570. Tools.Error("Invalid 'size' parameter !");
  7571. return;
  7572. }
  7573. var scene = camera.getScene();
  7574. var previousCamera = null;
  7575. if (scene.activeCamera !== camera) {
  7576. previousCamera = scene.activeCamera;
  7577. scene.activeCamera = camera;
  7578. }
  7579. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7580. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7581. texture.renderList = null;
  7582. texture.samples = samples;
  7583. if (antialiasing) {
  7584. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7585. }
  7586. texture.onAfterRenderObservable.add(function () {
  7587. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7588. });
  7589. scene.incrementRenderId();
  7590. scene.resetCachedMaterial();
  7591. texture.render(true);
  7592. texture.dispose();
  7593. if (previousCamera) {
  7594. scene.activeCamera = previousCamera;
  7595. }
  7596. camera.getProjectionMatrix(true); // Force cache refresh;
  7597. };
  7598. // XHR response validator for local file scenario
  7599. Tools.ValidateXHRData = function (xhr, dataType) {
  7600. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7601. if (dataType === void 0) { dataType = 7; }
  7602. try {
  7603. if (dataType & 1) {
  7604. if (xhr.responseText && xhr.responseText.length > 0) {
  7605. return true;
  7606. }
  7607. else if (dataType === 1) {
  7608. return false;
  7609. }
  7610. }
  7611. if (dataType & 2) {
  7612. // Check header width and height since there is no "TGA" magic number
  7613. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7614. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7615. return true;
  7616. }
  7617. else if (dataType === 2) {
  7618. return false;
  7619. }
  7620. }
  7621. if (dataType & 4) {
  7622. // Check for the "DDS" magic number
  7623. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7624. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7625. return true;
  7626. }
  7627. else {
  7628. return false;
  7629. }
  7630. }
  7631. }
  7632. catch (e) {
  7633. // Global protection
  7634. }
  7635. return false;
  7636. };
  7637. /**
  7638. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7639. * Be aware Math.random() could cause collisions, but:
  7640. * "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"
  7641. */
  7642. Tools.RandomId = function () {
  7643. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7644. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7645. return v.toString(16);
  7646. });
  7647. };
  7648. Object.defineProperty(Tools, "NoneLogLevel", {
  7649. get: function () {
  7650. return Tools._NoneLogLevel;
  7651. },
  7652. enumerable: true,
  7653. configurable: true
  7654. });
  7655. Object.defineProperty(Tools, "MessageLogLevel", {
  7656. get: function () {
  7657. return Tools._MessageLogLevel;
  7658. },
  7659. enumerable: true,
  7660. configurable: true
  7661. });
  7662. Object.defineProperty(Tools, "WarningLogLevel", {
  7663. get: function () {
  7664. return Tools._WarningLogLevel;
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. Object.defineProperty(Tools, "ErrorLogLevel", {
  7670. get: function () {
  7671. return Tools._ErrorLogLevel;
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Object.defineProperty(Tools, "AllLogLevel", {
  7677. get: function () {
  7678. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7679. },
  7680. enumerable: true,
  7681. configurable: true
  7682. });
  7683. Tools._AddLogEntry = function (entry) {
  7684. Tools._LogCache = entry + Tools._LogCache;
  7685. if (Tools.OnNewCacheEntry) {
  7686. Tools.OnNewCacheEntry(entry);
  7687. }
  7688. };
  7689. Tools._FormatMessage = function (message) {
  7690. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7691. var date = new Date();
  7692. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7693. };
  7694. Tools._LogDisabled = function (message) {
  7695. // nothing to do
  7696. };
  7697. Tools._LogEnabled = function (message) {
  7698. var formattedMessage = Tools._FormatMessage(message);
  7699. console.log("BJS - " + formattedMessage);
  7700. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7701. Tools._AddLogEntry(entry);
  7702. };
  7703. Tools._WarnDisabled = function (message) {
  7704. // nothing to do
  7705. };
  7706. Tools._WarnEnabled = function (message) {
  7707. var formattedMessage = Tools._FormatMessage(message);
  7708. console.warn("BJS - " + formattedMessage);
  7709. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7710. Tools._AddLogEntry(entry);
  7711. };
  7712. Tools._ErrorDisabled = function (message) {
  7713. // nothing to do
  7714. };
  7715. Tools._ErrorEnabled = function (message) {
  7716. Tools.errorsCount++;
  7717. var formattedMessage = Tools._FormatMessage(message);
  7718. console.error("BJS - " + formattedMessage);
  7719. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7720. Tools._AddLogEntry(entry);
  7721. };
  7722. Object.defineProperty(Tools, "LogCache", {
  7723. get: function () {
  7724. return Tools._LogCache;
  7725. },
  7726. enumerable: true,
  7727. configurable: true
  7728. });
  7729. Tools.ClearLogCache = function () {
  7730. Tools._LogCache = "";
  7731. Tools.errorsCount = 0;
  7732. };
  7733. Object.defineProperty(Tools, "LogLevels", {
  7734. set: function (level) {
  7735. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7736. Tools.Log = Tools._LogEnabled;
  7737. }
  7738. else {
  7739. Tools.Log = Tools._LogDisabled;
  7740. }
  7741. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7742. Tools.Warn = Tools._WarnEnabled;
  7743. }
  7744. else {
  7745. Tools.Warn = Tools._WarnDisabled;
  7746. }
  7747. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7748. Tools.Error = Tools._ErrorEnabled;
  7749. }
  7750. else {
  7751. Tools.Error = Tools._ErrorDisabled;
  7752. }
  7753. },
  7754. enumerable: true,
  7755. configurable: true
  7756. });
  7757. Tools.IsWindowObjectExist = function () {
  7758. return (typeof window) !== "undefined";
  7759. };
  7760. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7761. get: function () {
  7762. return Tools._PerformanceNoneLogLevel;
  7763. },
  7764. enumerable: true,
  7765. configurable: true
  7766. });
  7767. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7768. get: function () {
  7769. return Tools._PerformanceUserMarkLogLevel;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7775. get: function () {
  7776. return Tools._PerformanceConsoleLogLevel;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7782. set: function (level) {
  7783. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7784. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7785. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7786. return;
  7787. }
  7788. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7789. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7790. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7791. return;
  7792. }
  7793. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7794. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7795. },
  7796. enumerable: true,
  7797. configurable: true
  7798. });
  7799. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7800. };
  7801. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7802. };
  7803. Tools._StartUserMark = function (counterName, condition) {
  7804. if (condition === void 0) { condition = true; }
  7805. if (!Tools._performance) {
  7806. if (!Tools.IsWindowObjectExist()) {
  7807. return;
  7808. }
  7809. Tools._performance = window.performance;
  7810. }
  7811. if (!condition || !Tools._performance.mark) {
  7812. return;
  7813. }
  7814. Tools._performance.mark(counterName + "-Begin");
  7815. };
  7816. Tools._EndUserMark = function (counterName, condition) {
  7817. if (condition === void 0) { condition = true; }
  7818. if (!condition || !Tools._performance.mark) {
  7819. return;
  7820. }
  7821. Tools._performance.mark(counterName + "-End");
  7822. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7823. };
  7824. Tools._StartPerformanceConsole = function (counterName, condition) {
  7825. if (condition === void 0) { condition = true; }
  7826. if (!condition) {
  7827. return;
  7828. }
  7829. Tools._StartUserMark(counterName, condition);
  7830. if (console.time) {
  7831. console.time(counterName);
  7832. }
  7833. };
  7834. Tools._EndPerformanceConsole = function (counterName, condition) {
  7835. if (condition === void 0) { condition = true; }
  7836. if (!condition) {
  7837. return;
  7838. }
  7839. Tools._EndUserMark(counterName, condition);
  7840. if (console.time) {
  7841. console.timeEnd(counterName);
  7842. }
  7843. };
  7844. Object.defineProperty(Tools, "Now", {
  7845. get: function () {
  7846. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7847. return window.performance.now();
  7848. }
  7849. return new Date().getTime();
  7850. },
  7851. enumerable: true,
  7852. configurable: true
  7853. });
  7854. /**
  7855. * This method will return the name of the class used to create the instance of the given object.
  7856. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7857. * @param object the object to get the class name from
  7858. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7859. */
  7860. Tools.GetClassName = function (object, isType) {
  7861. if (isType === void 0) { isType = false; }
  7862. var name = null;
  7863. if (!isType && object.getClassName) {
  7864. name = object.getClassName();
  7865. }
  7866. else {
  7867. if (object instanceof Object) {
  7868. var classObj = isType ? object : Object.getPrototypeOf(object);
  7869. name = classObj.constructor["__bjsclassName__"];
  7870. }
  7871. if (!name) {
  7872. name = typeof object;
  7873. }
  7874. }
  7875. return name;
  7876. };
  7877. Tools.First = function (array, predicate) {
  7878. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7879. var el = array_1[_i];
  7880. if (predicate(el)) {
  7881. return el;
  7882. }
  7883. }
  7884. return null;
  7885. };
  7886. /**
  7887. * This method will return the name of the full name of the class, including its owning module (if any).
  7888. * 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).
  7889. * @param object the object to get the class name from
  7890. * @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.
  7891. */
  7892. Tools.getFullClassName = function (object, isType) {
  7893. if (isType === void 0) { isType = false; }
  7894. var className = null;
  7895. var moduleName = null;
  7896. if (!isType && object.getClassName) {
  7897. className = object.getClassName();
  7898. }
  7899. else {
  7900. if (object instanceof Object) {
  7901. var classObj = isType ? object : Object.getPrototypeOf(object);
  7902. className = classObj.constructor["__bjsclassName__"];
  7903. moduleName = classObj.constructor["__bjsmoduleName__"];
  7904. }
  7905. if (!className) {
  7906. className = typeof object;
  7907. }
  7908. }
  7909. if (!className) {
  7910. return null;
  7911. }
  7912. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7913. };
  7914. /**
  7915. * 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.
  7916. * @param array
  7917. */
  7918. Tools.arrayOrStringFeeder = function (array) {
  7919. return function (index) {
  7920. if (index >= array.length) {
  7921. return null;
  7922. }
  7923. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7924. if (val && val.getHashCode) {
  7925. val = val.getHashCode();
  7926. }
  7927. if (typeof val === "string") {
  7928. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7929. }
  7930. return val;
  7931. };
  7932. };
  7933. /**
  7934. * Compute the hashCode of a stream of number
  7935. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7936. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7937. * @return the hash code computed
  7938. */
  7939. Tools.hashCodeFromStream = function (feeder) {
  7940. // Based from here: http://stackoverflow.com/a/7616484/802124
  7941. var hash = 0;
  7942. var index = 0;
  7943. var chr = feeder(index++);
  7944. while (chr != null) {
  7945. hash = ((hash << 5) - hash) + chr;
  7946. hash |= 0; // Convert to 32bit integer
  7947. chr = feeder(index++);
  7948. }
  7949. return hash;
  7950. };
  7951. Tools.BaseUrl = "";
  7952. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7953. /**
  7954. * Default behaviour for cors in the application.
  7955. * It can be a string if the expected behavior is identical in the entire app.
  7956. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7957. */
  7958. Tools.CorsBehavior = "anonymous";
  7959. Tools.UseFallbackTexture = true;
  7960. /**
  7961. * Use this object to register external classes like custom textures or material
  7962. * to allow the laoders to instantiate them
  7963. */
  7964. Tools.RegisteredExternalClasses = {};
  7965. // Used in case of a texture loading problem
  7966. 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";
  7967. Tools.PreprocessUrl = function (url) {
  7968. return url;
  7969. };
  7970. // Logs
  7971. Tools._NoneLogLevel = 0;
  7972. Tools._MessageLogLevel = 1;
  7973. Tools._WarningLogLevel = 2;
  7974. Tools._ErrorLogLevel = 4;
  7975. Tools._LogCache = "";
  7976. Tools.errorsCount = 0;
  7977. Tools.Log = Tools._LogEnabled;
  7978. Tools.Warn = Tools._WarnEnabled;
  7979. Tools.Error = Tools._ErrorEnabled;
  7980. // Performances
  7981. Tools._PerformanceNoneLogLevel = 0;
  7982. Tools._PerformanceUserMarkLogLevel = 1;
  7983. Tools._PerformanceConsoleLogLevel = 2;
  7984. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7985. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7986. return Tools;
  7987. }());
  7988. BABYLON.Tools = Tools;
  7989. /**
  7990. * This class is used to track a performance counter which is number based.
  7991. * The user has access to many properties which give statistics of different nature
  7992. *
  7993. * The implementer can track two kinds of Performance Counter: time and count
  7994. * 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.
  7995. * 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.
  7996. */
  7997. var PerfCounter = /** @class */ (function () {
  7998. function PerfCounter() {
  7999. this._startMonitoringTime = 0;
  8000. this._min = 0;
  8001. this._max = 0;
  8002. this._average = 0;
  8003. this._lastSecAverage = 0;
  8004. this._current = 0;
  8005. this._totalValueCount = 0;
  8006. this._totalAccumulated = 0;
  8007. this._lastSecAccumulated = 0;
  8008. this._lastSecTime = 0;
  8009. this._lastSecValueCount = 0;
  8010. }
  8011. Object.defineProperty(PerfCounter.prototype, "min", {
  8012. /**
  8013. * Returns the smallest value ever
  8014. */
  8015. get: function () {
  8016. return this._min;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. Object.defineProperty(PerfCounter.prototype, "max", {
  8022. /**
  8023. * Returns the biggest value ever
  8024. */
  8025. get: function () {
  8026. return this._max;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(PerfCounter.prototype, "average", {
  8032. /**
  8033. * Returns the average value since the performance counter is running
  8034. */
  8035. get: function () {
  8036. return this._average;
  8037. },
  8038. enumerable: true,
  8039. configurable: true
  8040. });
  8041. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8042. /**
  8043. * Returns the average value of the last second the counter was monitored
  8044. */
  8045. get: function () {
  8046. return this._lastSecAverage;
  8047. },
  8048. enumerable: true,
  8049. configurable: true
  8050. });
  8051. Object.defineProperty(PerfCounter.prototype, "current", {
  8052. /**
  8053. * Returns the current value
  8054. */
  8055. get: function () {
  8056. return this._current;
  8057. },
  8058. enumerable: true,
  8059. configurable: true
  8060. });
  8061. Object.defineProperty(PerfCounter.prototype, "total", {
  8062. get: function () {
  8063. return this._totalAccumulated;
  8064. },
  8065. enumerable: true,
  8066. configurable: true
  8067. });
  8068. Object.defineProperty(PerfCounter.prototype, "count", {
  8069. get: function () {
  8070. return this._totalValueCount;
  8071. },
  8072. enumerable: true,
  8073. configurable: true
  8074. });
  8075. /**
  8076. * Call this method to start monitoring a new frame.
  8077. * 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.
  8078. */
  8079. PerfCounter.prototype.fetchNewFrame = function () {
  8080. this._totalValueCount++;
  8081. this._current = 0;
  8082. this._lastSecValueCount++;
  8083. };
  8084. /**
  8085. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8086. * @param newCount the count value to add to the monitored count
  8087. * @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.
  8088. */
  8089. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8090. if (!PerfCounter.Enabled) {
  8091. return;
  8092. }
  8093. this._current += newCount;
  8094. if (fetchResult) {
  8095. this._fetchResult();
  8096. }
  8097. };
  8098. /**
  8099. * Start monitoring this performance counter
  8100. */
  8101. PerfCounter.prototype.beginMonitoring = function () {
  8102. if (!PerfCounter.Enabled) {
  8103. return;
  8104. }
  8105. this._startMonitoringTime = Tools.Now;
  8106. };
  8107. /**
  8108. * Compute the time lapsed since the previous beginMonitoring() call.
  8109. * @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
  8110. */
  8111. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8112. if (newFrame === void 0) { newFrame = true; }
  8113. if (!PerfCounter.Enabled) {
  8114. return;
  8115. }
  8116. if (newFrame) {
  8117. this.fetchNewFrame();
  8118. }
  8119. var currentTime = Tools.Now;
  8120. this._current = currentTime - this._startMonitoringTime;
  8121. if (newFrame) {
  8122. this._fetchResult();
  8123. }
  8124. };
  8125. PerfCounter.prototype._fetchResult = function () {
  8126. this._totalAccumulated += this._current;
  8127. this._lastSecAccumulated += this._current;
  8128. // Min/Max update
  8129. this._min = Math.min(this._min, this._current);
  8130. this._max = Math.max(this._max, this._current);
  8131. this._average = this._totalAccumulated / this._totalValueCount;
  8132. // Reset last sec?
  8133. var now = Tools.Now;
  8134. if ((now - this._lastSecTime) > 1000) {
  8135. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8136. this._lastSecTime = now;
  8137. this._lastSecAccumulated = 0;
  8138. this._lastSecValueCount = 0;
  8139. }
  8140. };
  8141. PerfCounter.Enabled = true;
  8142. return PerfCounter;
  8143. }());
  8144. BABYLON.PerfCounter = PerfCounter;
  8145. /**
  8146. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8147. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8148. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8149. * @param name The name of the class, case should be preserved
  8150. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8151. */
  8152. function className(name, module) {
  8153. return function (target) {
  8154. target["__bjsclassName__"] = name;
  8155. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8156. };
  8157. }
  8158. BABYLON.className = className;
  8159. /**
  8160. * An implementation of a loop for asynchronous functions.
  8161. */
  8162. var AsyncLoop = /** @class */ (function () {
  8163. /**
  8164. * Constroctor.
  8165. * @param iterations the number of iterations.
  8166. * @param _fn the function to run each iteration
  8167. * @param _successCallback the callback that will be called upon succesful execution
  8168. * @param offset starting offset.
  8169. */
  8170. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8171. if (offset === void 0) { offset = 0; }
  8172. this.iterations = iterations;
  8173. this._fn = _fn;
  8174. this._successCallback = _successCallback;
  8175. this.index = offset - 1;
  8176. this._done = false;
  8177. }
  8178. /**
  8179. * Execute the next iteration. Must be called after the last iteration was finished.
  8180. */
  8181. AsyncLoop.prototype.executeNext = function () {
  8182. if (!this._done) {
  8183. if (this.index + 1 < this.iterations) {
  8184. ++this.index;
  8185. this._fn(this);
  8186. }
  8187. else {
  8188. this.breakLoop();
  8189. }
  8190. }
  8191. };
  8192. /**
  8193. * Break the loop and run the success callback.
  8194. */
  8195. AsyncLoop.prototype.breakLoop = function () {
  8196. this._done = true;
  8197. this._successCallback();
  8198. };
  8199. /**
  8200. * Helper function
  8201. */
  8202. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8203. if (offset === void 0) { offset = 0; }
  8204. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8205. loop.executeNext();
  8206. return loop;
  8207. };
  8208. /**
  8209. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8210. * @param iterations total number of iterations
  8211. * @param syncedIterations number of synchronous iterations in each async iteration.
  8212. * @param fn the function to call each iteration.
  8213. * @param callback a success call back that will be called when iterating stops.
  8214. * @param breakFunction a break condition (optional)
  8215. * @param timeout timeout settings for the setTimeout function. default - 0.
  8216. * @constructor
  8217. */
  8218. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8219. if (timeout === void 0) { timeout = 0; }
  8220. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8221. if (breakFunction && breakFunction())
  8222. loop.breakLoop();
  8223. else {
  8224. setTimeout(function () {
  8225. for (var i = 0; i < syncedIterations; ++i) {
  8226. var iteration = (loop.index * syncedIterations) + i;
  8227. if (iteration >= iterations)
  8228. break;
  8229. fn(iteration);
  8230. if (breakFunction && breakFunction()) {
  8231. loop.breakLoop();
  8232. break;
  8233. }
  8234. }
  8235. loop.executeNext();
  8236. }, timeout);
  8237. }
  8238. }, callback);
  8239. };
  8240. return AsyncLoop;
  8241. }());
  8242. BABYLON.AsyncLoop = AsyncLoop;
  8243. })(BABYLON || (BABYLON = {}));
  8244. //# sourceMappingURL=babylon.tools.js.map
  8245. var BABYLON;
  8246. (function (BABYLON) {
  8247. var _AlphaState = /** @class */ (function () {
  8248. /**
  8249. * Initializes the state.
  8250. */
  8251. function _AlphaState() {
  8252. this._isAlphaBlendDirty = false;
  8253. this._isBlendFunctionParametersDirty = false;
  8254. this._isBlendEquationParametersDirty = false;
  8255. this._isBlendConstantsDirty = false;
  8256. this._alphaBlend = false;
  8257. this._blendFunctionParameters = new Array(4);
  8258. this._blendEquationParameters = new Array(2);
  8259. this._blendConstants = new Array(4);
  8260. this.reset();
  8261. }
  8262. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8263. get: function () {
  8264. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8265. },
  8266. enumerable: true,
  8267. configurable: true
  8268. });
  8269. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8270. get: function () {
  8271. return this._alphaBlend;
  8272. },
  8273. set: function (value) {
  8274. if (this._alphaBlend === value) {
  8275. return;
  8276. }
  8277. this._alphaBlend = value;
  8278. this._isAlphaBlendDirty = true;
  8279. },
  8280. enumerable: true,
  8281. configurable: true
  8282. });
  8283. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8284. if (this._blendConstants[0] === r &&
  8285. this._blendConstants[1] === g &&
  8286. this._blendConstants[2] === b &&
  8287. this._blendConstants[3] === a) {
  8288. return;
  8289. }
  8290. this._blendConstants[0] = r;
  8291. this._blendConstants[1] = g;
  8292. this._blendConstants[2] = b;
  8293. this._blendConstants[3] = a;
  8294. this._isBlendConstantsDirty = true;
  8295. };
  8296. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8297. if (this._blendFunctionParameters[0] === value0 &&
  8298. this._blendFunctionParameters[1] === value1 &&
  8299. this._blendFunctionParameters[2] === value2 &&
  8300. this._blendFunctionParameters[3] === value3) {
  8301. return;
  8302. }
  8303. this._blendFunctionParameters[0] = value0;
  8304. this._blendFunctionParameters[1] = value1;
  8305. this._blendFunctionParameters[2] = value2;
  8306. this._blendFunctionParameters[3] = value3;
  8307. this._isBlendFunctionParametersDirty = true;
  8308. };
  8309. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8310. if (this._blendEquationParameters[0] === rgb &&
  8311. this._blendEquationParameters[1] === alpha) {
  8312. return;
  8313. }
  8314. this._blendEquationParameters[0] = rgb;
  8315. this._blendEquationParameters[1] = alpha;
  8316. this._isBlendEquationParametersDirty = true;
  8317. };
  8318. _AlphaState.prototype.reset = function () {
  8319. this._alphaBlend = false;
  8320. this._blendFunctionParameters[0] = null;
  8321. this._blendFunctionParameters[1] = null;
  8322. this._blendFunctionParameters[2] = null;
  8323. this._blendFunctionParameters[3] = null;
  8324. this._blendEquationParameters[0] = null;
  8325. this._blendEquationParameters[1] = null;
  8326. this._blendConstants[0] = null;
  8327. this._blendConstants[1] = null;
  8328. this._blendConstants[2] = null;
  8329. this._blendConstants[3] = null;
  8330. this._isAlphaBlendDirty = true;
  8331. this._isBlendFunctionParametersDirty = false;
  8332. this._isBlendEquationParametersDirty = false;
  8333. this._isBlendConstantsDirty = false;
  8334. };
  8335. _AlphaState.prototype.apply = function (gl) {
  8336. if (!this.isDirty) {
  8337. return;
  8338. }
  8339. // Alpha blend
  8340. if (this._isAlphaBlendDirty) {
  8341. if (this._alphaBlend) {
  8342. gl.enable(gl.BLEND);
  8343. }
  8344. else {
  8345. gl.disable(gl.BLEND);
  8346. }
  8347. this._isAlphaBlendDirty = false;
  8348. }
  8349. // Alpha function
  8350. if (this._isBlendFunctionParametersDirty) {
  8351. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8352. this._isBlendFunctionParametersDirty = false;
  8353. }
  8354. // Alpha equation
  8355. if (this._isBlendEquationParametersDirty) {
  8356. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8357. this._isBlendEquationParametersDirty = false;
  8358. }
  8359. // Constants
  8360. if (this._isBlendConstantsDirty) {
  8361. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8362. this._isBlendConstantsDirty = false;
  8363. }
  8364. };
  8365. return _AlphaState;
  8366. }());
  8367. BABYLON._AlphaState = _AlphaState;
  8368. })(BABYLON || (BABYLON = {}));
  8369. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8370. var BABYLON;
  8371. (function (BABYLON) {
  8372. var _DepthCullingState = /** @class */ (function () {
  8373. /**
  8374. * Initializes the state.
  8375. */
  8376. function _DepthCullingState() {
  8377. this._isDepthTestDirty = false;
  8378. this._isDepthMaskDirty = false;
  8379. this._isDepthFuncDirty = false;
  8380. this._isCullFaceDirty = false;
  8381. this._isCullDirty = false;
  8382. this._isZOffsetDirty = false;
  8383. this._isFrontFaceDirty = false;
  8384. this.reset();
  8385. }
  8386. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8387. get: function () {
  8388. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8389. },
  8390. enumerable: true,
  8391. configurable: true
  8392. });
  8393. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8394. get: function () {
  8395. return this._zOffset;
  8396. },
  8397. set: function (value) {
  8398. if (this._zOffset === value) {
  8399. return;
  8400. }
  8401. this._zOffset = value;
  8402. this._isZOffsetDirty = true;
  8403. },
  8404. enumerable: true,
  8405. configurable: true
  8406. });
  8407. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8408. get: function () {
  8409. return this._cullFace;
  8410. },
  8411. set: function (value) {
  8412. if (this._cullFace === value) {
  8413. return;
  8414. }
  8415. this._cullFace = value;
  8416. this._isCullFaceDirty = true;
  8417. },
  8418. enumerable: true,
  8419. configurable: true
  8420. });
  8421. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8422. get: function () {
  8423. return this._cull;
  8424. },
  8425. set: function (value) {
  8426. if (this._cull === value) {
  8427. return;
  8428. }
  8429. this._cull = value;
  8430. this._isCullDirty = true;
  8431. },
  8432. enumerable: true,
  8433. configurable: true
  8434. });
  8435. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8436. get: function () {
  8437. return this._depthFunc;
  8438. },
  8439. set: function (value) {
  8440. if (this._depthFunc === value) {
  8441. return;
  8442. }
  8443. this._depthFunc = value;
  8444. this._isDepthFuncDirty = true;
  8445. },
  8446. enumerable: true,
  8447. configurable: true
  8448. });
  8449. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8450. get: function () {
  8451. return this._depthMask;
  8452. },
  8453. set: function (value) {
  8454. if (this._depthMask === value) {
  8455. return;
  8456. }
  8457. this._depthMask = value;
  8458. this._isDepthMaskDirty = true;
  8459. },
  8460. enumerable: true,
  8461. configurable: true
  8462. });
  8463. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8464. get: function () {
  8465. return this._depthTest;
  8466. },
  8467. set: function (value) {
  8468. if (this._depthTest === value) {
  8469. return;
  8470. }
  8471. this._depthTest = value;
  8472. this._isDepthTestDirty = true;
  8473. },
  8474. enumerable: true,
  8475. configurable: true
  8476. });
  8477. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8478. get: function () {
  8479. return this._frontFace;
  8480. },
  8481. set: function (value) {
  8482. if (this._frontFace === value) {
  8483. return;
  8484. }
  8485. this._frontFace = value;
  8486. this._isFrontFaceDirty = true;
  8487. },
  8488. enumerable: true,
  8489. configurable: true
  8490. });
  8491. _DepthCullingState.prototype.reset = function () {
  8492. this._depthMask = true;
  8493. this._depthTest = true;
  8494. this._depthFunc = null;
  8495. this._cullFace = null;
  8496. this._cull = null;
  8497. this._zOffset = 0;
  8498. this._frontFace = null;
  8499. this._isDepthTestDirty = true;
  8500. this._isDepthMaskDirty = true;
  8501. this._isDepthFuncDirty = false;
  8502. this._isCullFaceDirty = false;
  8503. this._isCullDirty = false;
  8504. this._isZOffsetDirty = false;
  8505. this._isFrontFaceDirty = false;
  8506. };
  8507. _DepthCullingState.prototype.apply = function (gl) {
  8508. if (!this.isDirty) {
  8509. return;
  8510. }
  8511. // Cull
  8512. if (this._isCullDirty) {
  8513. if (this.cull) {
  8514. gl.enable(gl.CULL_FACE);
  8515. }
  8516. else {
  8517. gl.disable(gl.CULL_FACE);
  8518. }
  8519. this._isCullDirty = false;
  8520. }
  8521. // Cull face
  8522. if (this._isCullFaceDirty) {
  8523. gl.cullFace(this.cullFace);
  8524. this._isCullFaceDirty = false;
  8525. }
  8526. // Depth mask
  8527. if (this._isDepthMaskDirty) {
  8528. gl.depthMask(this.depthMask);
  8529. this._isDepthMaskDirty = false;
  8530. }
  8531. // Depth test
  8532. if (this._isDepthTestDirty) {
  8533. if (this.depthTest) {
  8534. gl.enable(gl.DEPTH_TEST);
  8535. }
  8536. else {
  8537. gl.disable(gl.DEPTH_TEST);
  8538. }
  8539. this._isDepthTestDirty = false;
  8540. }
  8541. // Depth func
  8542. if (this._isDepthFuncDirty) {
  8543. gl.depthFunc(this.depthFunc);
  8544. this._isDepthFuncDirty = false;
  8545. }
  8546. // zOffset
  8547. if (this._isZOffsetDirty) {
  8548. if (this.zOffset) {
  8549. gl.enable(gl.POLYGON_OFFSET_FILL);
  8550. gl.polygonOffset(this.zOffset, 0);
  8551. }
  8552. else {
  8553. gl.disable(gl.POLYGON_OFFSET_FILL);
  8554. }
  8555. this._isZOffsetDirty = false;
  8556. }
  8557. // Front face
  8558. if (this._isFrontFaceDirty) {
  8559. gl.frontFace(this.frontFace);
  8560. this._isFrontFaceDirty = false;
  8561. }
  8562. };
  8563. return _DepthCullingState;
  8564. }());
  8565. BABYLON._DepthCullingState = _DepthCullingState;
  8566. })(BABYLON || (BABYLON = {}));
  8567. //# sourceMappingURL=babylon.depthCullingState.js.map
  8568. var BABYLON;
  8569. (function (BABYLON) {
  8570. var _StencilState = /** @class */ (function () {
  8571. function _StencilState() {
  8572. this._isStencilTestDirty = false;
  8573. this._isStencilMaskDirty = false;
  8574. this._isStencilFuncDirty = false;
  8575. this._isStencilOpDirty = false;
  8576. this.reset();
  8577. }
  8578. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8579. get: function () {
  8580. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8581. },
  8582. enumerable: true,
  8583. configurable: true
  8584. });
  8585. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8586. get: function () {
  8587. return this._stencilFunc;
  8588. },
  8589. set: function (value) {
  8590. if (this._stencilFunc === value) {
  8591. return;
  8592. }
  8593. this._stencilFunc = value;
  8594. this._isStencilFuncDirty = true;
  8595. },
  8596. enumerable: true,
  8597. configurable: true
  8598. });
  8599. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8600. get: function () {
  8601. return this._stencilFuncRef;
  8602. },
  8603. set: function (value) {
  8604. if (this._stencilFuncRef === value) {
  8605. return;
  8606. }
  8607. this._stencilFuncRef = value;
  8608. this._isStencilFuncDirty = true;
  8609. },
  8610. enumerable: true,
  8611. configurable: true
  8612. });
  8613. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8614. get: function () {
  8615. return this._stencilFuncMask;
  8616. },
  8617. set: function (value) {
  8618. if (this._stencilFuncMask === value) {
  8619. return;
  8620. }
  8621. this._stencilFuncMask = value;
  8622. this._isStencilFuncDirty = true;
  8623. },
  8624. enumerable: true,
  8625. configurable: true
  8626. });
  8627. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8628. get: function () {
  8629. return this._stencilOpStencilFail;
  8630. },
  8631. set: function (value) {
  8632. if (this._stencilOpStencilFail === value) {
  8633. return;
  8634. }
  8635. this._stencilOpStencilFail = value;
  8636. this._isStencilOpDirty = true;
  8637. },
  8638. enumerable: true,
  8639. configurable: true
  8640. });
  8641. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8642. get: function () {
  8643. return this._stencilOpDepthFail;
  8644. },
  8645. set: function (value) {
  8646. if (this._stencilOpDepthFail === value) {
  8647. return;
  8648. }
  8649. this._stencilOpDepthFail = value;
  8650. this._isStencilOpDirty = true;
  8651. },
  8652. enumerable: true,
  8653. configurable: true
  8654. });
  8655. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8656. get: function () {
  8657. return this._stencilOpStencilDepthPass;
  8658. },
  8659. set: function (value) {
  8660. if (this._stencilOpStencilDepthPass === value) {
  8661. return;
  8662. }
  8663. this._stencilOpStencilDepthPass = value;
  8664. this._isStencilOpDirty = true;
  8665. },
  8666. enumerable: true,
  8667. configurable: true
  8668. });
  8669. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8670. get: function () {
  8671. return this._stencilMask;
  8672. },
  8673. set: function (value) {
  8674. if (this._stencilMask === value) {
  8675. return;
  8676. }
  8677. this._stencilMask = value;
  8678. this._isStencilMaskDirty = true;
  8679. },
  8680. enumerable: true,
  8681. configurable: true
  8682. });
  8683. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8684. get: function () {
  8685. return this._stencilTest;
  8686. },
  8687. set: function (value) {
  8688. if (this._stencilTest === value) {
  8689. return;
  8690. }
  8691. this._stencilTest = value;
  8692. this._isStencilTestDirty = true;
  8693. },
  8694. enumerable: true,
  8695. configurable: true
  8696. });
  8697. _StencilState.prototype.reset = function () {
  8698. this._stencilTest = false;
  8699. this._stencilMask = 0xFF;
  8700. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8701. this._stencilFuncRef = 1;
  8702. this._stencilFuncMask = 0xFF;
  8703. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8704. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8705. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8706. this._isStencilTestDirty = true;
  8707. this._isStencilMaskDirty = true;
  8708. this._isStencilFuncDirty = true;
  8709. this._isStencilOpDirty = true;
  8710. };
  8711. _StencilState.prototype.apply = function (gl) {
  8712. if (!this.isDirty) {
  8713. return;
  8714. }
  8715. // Stencil test
  8716. if (this._isStencilTestDirty) {
  8717. if (this.stencilTest) {
  8718. gl.enable(gl.STENCIL_TEST);
  8719. }
  8720. else {
  8721. gl.disable(gl.STENCIL_TEST);
  8722. }
  8723. this._isStencilTestDirty = false;
  8724. }
  8725. // Stencil mask
  8726. if (this._isStencilMaskDirty) {
  8727. gl.stencilMask(this.stencilMask);
  8728. this._isStencilMaskDirty = false;
  8729. }
  8730. // Stencil func
  8731. if (this._isStencilFuncDirty) {
  8732. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8733. this._isStencilFuncDirty = false;
  8734. }
  8735. // Stencil op
  8736. if (this._isStencilOpDirty) {
  8737. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8738. this._isStencilOpDirty = false;
  8739. }
  8740. };
  8741. return _StencilState;
  8742. }());
  8743. BABYLON._StencilState = _StencilState;
  8744. })(BABYLON || (BABYLON = {}));
  8745. //# sourceMappingURL=babylon.stencilState.js.map
  8746. var BABYLON;
  8747. (function (BABYLON) {
  8748. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8749. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8750. };
  8751. var compileRawShader = function (gl, source, type) {
  8752. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8753. gl.shaderSource(shader, source);
  8754. gl.compileShader(shader);
  8755. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8756. var log = gl.getShaderInfoLog(shader);
  8757. if (log) {
  8758. throw new Error(log);
  8759. }
  8760. }
  8761. if (!shader) {
  8762. throw new Error("Something went wrong while compile the shader.");
  8763. }
  8764. return shader;
  8765. };
  8766. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8767. var magFilter = gl.NEAREST;
  8768. var minFilter = gl.NEAREST;
  8769. switch (samplingMode) {
  8770. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8771. magFilter = gl.LINEAR;
  8772. if (generateMipMaps) {
  8773. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8774. }
  8775. else {
  8776. minFilter = gl.LINEAR;
  8777. }
  8778. break;
  8779. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8780. magFilter = gl.LINEAR;
  8781. if (generateMipMaps) {
  8782. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8783. }
  8784. else {
  8785. minFilter = gl.LINEAR;
  8786. }
  8787. break;
  8788. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8789. magFilter = gl.NEAREST;
  8790. if (generateMipMaps) {
  8791. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8792. }
  8793. else {
  8794. minFilter = gl.NEAREST;
  8795. }
  8796. break;
  8797. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8798. magFilter = gl.NEAREST;
  8799. if (generateMipMaps) {
  8800. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8801. }
  8802. else {
  8803. minFilter = gl.NEAREST;
  8804. }
  8805. break;
  8806. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8807. magFilter = gl.NEAREST;
  8808. if (generateMipMaps) {
  8809. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8810. }
  8811. else {
  8812. minFilter = gl.LINEAR;
  8813. }
  8814. break;
  8815. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8816. magFilter = gl.NEAREST;
  8817. if (generateMipMaps) {
  8818. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8819. }
  8820. else {
  8821. minFilter = gl.LINEAR;
  8822. }
  8823. break;
  8824. case BABYLON.Texture.NEAREST_LINEAR:
  8825. magFilter = gl.NEAREST;
  8826. minFilter = gl.LINEAR;
  8827. break;
  8828. case BABYLON.Texture.NEAREST_NEAREST:
  8829. magFilter = gl.NEAREST;
  8830. minFilter = gl.NEAREST;
  8831. break;
  8832. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8833. magFilter = gl.LINEAR;
  8834. if (generateMipMaps) {
  8835. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8836. }
  8837. else {
  8838. minFilter = gl.NEAREST;
  8839. }
  8840. break;
  8841. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8842. magFilter = gl.LINEAR;
  8843. if (generateMipMaps) {
  8844. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8845. }
  8846. else {
  8847. minFilter = gl.NEAREST;
  8848. }
  8849. break;
  8850. case BABYLON.Texture.LINEAR_LINEAR:
  8851. magFilter = gl.LINEAR;
  8852. minFilter = gl.LINEAR;
  8853. break;
  8854. case BABYLON.Texture.LINEAR_NEAREST:
  8855. magFilter = gl.LINEAR;
  8856. minFilter = gl.NEAREST;
  8857. break;
  8858. }
  8859. return {
  8860. min: minFilter,
  8861. mag: magFilter
  8862. };
  8863. };
  8864. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8865. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8866. var img;
  8867. var onload = function () {
  8868. loadedImages[index] = img;
  8869. loadedImages._internalCount++;
  8870. if (scene) {
  8871. scene._removePendingData(img);
  8872. }
  8873. if (loadedImages._internalCount === 6) {
  8874. onfinish(loadedImages);
  8875. }
  8876. };
  8877. var onerror = function (message, exception) {
  8878. if (scene) {
  8879. scene._removePendingData(img);
  8880. }
  8881. if (onErrorCallBack) {
  8882. onErrorCallBack(message, exception);
  8883. }
  8884. };
  8885. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8886. if (scene) {
  8887. scene._addPendingData(img);
  8888. }
  8889. };
  8890. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8891. if (onError === void 0) { onError = null; }
  8892. var loadedImages = [];
  8893. loadedImages._internalCount = 0;
  8894. for (var index = 0; index < 6; index++) {
  8895. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8896. }
  8897. };
  8898. var BufferPointer = /** @class */ (function () {
  8899. function BufferPointer() {
  8900. }
  8901. return BufferPointer;
  8902. }());
  8903. var InstancingAttributeInfo = /** @class */ (function () {
  8904. function InstancingAttributeInfo() {
  8905. }
  8906. return InstancingAttributeInfo;
  8907. }());
  8908. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8909. /**
  8910. * Define options used to create a render target texture
  8911. */
  8912. var RenderTargetCreationOptions = /** @class */ (function () {
  8913. function RenderTargetCreationOptions() {
  8914. }
  8915. return RenderTargetCreationOptions;
  8916. }());
  8917. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8918. /**
  8919. * Regroup several parameters relative to the browser in use
  8920. */
  8921. var EngineCapabilities = /** @class */ (function () {
  8922. function EngineCapabilities() {
  8923. }
  8924. return EngineCapabilities;
  8925. }());
  8926. BABYLON.EngineCapabilities = EngineCapabilities;
  8927. /**
  8928. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8929. */
  8930. var Engine = /** @class */ (function () {
  8931. /**
  8932. * @constructor
  8933. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  8934. * @param antialias defines enable antialiasing (default: false)
  8935. * @param options defines further options to be sent to the getContext() function
  8936. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  8937. */
  8938. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8939. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8940. var _this = this;
  8941. // Public members
  8942. this.forcePOTTextures = false;
  8943. this.isFullscreen = false;
  8944. this.isPointerLock = false;
  8945. this.cullBackFaces = true;
  8946. this.renderEvenInBackground = true;
  8947. this.preventCacheWipeBetweenFrames = false;
  8948. // To enable/disable IDB support and avoid XHR on .manifest
  8949. this.enableOfflineSupport = false;
  8950. this.scenes = new Array();
  8951. this.postProcesses = new Array();
  8952. // Observables
  8953. /**
  8954. * Observable event triggered each time the rendering canvas is resized
  8955. */
  8956. this.onResizeObservable = new BABYLON.Observable();
  8957. /**
  8958. * Observable event triggered each time the canvas loses focus
  8959. */
  8960. this.onCanvasBlurObservable = new BABYLON.Observable();
  8961. /**
  8962. * Observable event triggered each time the canvas gains focus
  8963. */
  8964. this.onCanvasFocusObservable = new BABYLON.Observable();
  8965. /**
  8966. * Observable event triggered each time the canvas receives pointerout event
  8967. */
  8968. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8969. /**
  8970. * Observable event triggered before each texture is initialized
  8971. */
  8972. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8973. //WebVR
  8974. this._vrDisplay = undefined;
  8975. this._vrSupported = false;
  8976. this._vrExclusivePointerMode = false;
  8977. // Uniform buffers list
  8978. this.disableUniformBuffers = false;
  8979. this._uniformBuffers = new Array();
  8980. // Observables
  8981. /**
  8982. * Observable raised when the engine begins a new frame
  8983. */
  8984. this.onBeginFrameObservable = new BABYLON.Observable();
  8985. /**
  8986. * Observable raised when the engine ends the current frame
  8987. */
  8988. this.onEndFrameObservable = new BABYLON.Observable();
  8989. /**
  8990. * Observable raised when the engine is about to compile a shader
  8991. */
  8992. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8993. /**
  8994. * Observable raised when the engine has jsut compiled a shader
  8995. */
  8996. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8997. this._windowIsBackground = false;
  8998. this._webGLVersion = 1.0;
  8999. this._badOS = false;
  9000. this._badDesktopOS = false;
  9001. /**
  9002. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9003. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9004. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9005. */
  9006. this.disableTextureBindingOptimization = false;
  9007. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9008. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9009. this.onVRRequestPresentStart = new BABYLON.Observable();
  9010. this._colorWrite = true;
  9011. this._drawCalls = new BABYLON.PerfCounter();
  9012. this._textureCollisions = new BABYLON.PerfCounter();
  9013. this._renderingQueueLaunched = false;
  9014. this._activeRenderLoops = new Array();
  9015. // Deterministic lockstepMaxSteps
  9016. this._deterministicLockstep = false;
  9017. this._lockstepMaxSteps = 4;
  9018. // Lost context
  9019. this.onContextLostObservable = new BABYLON.Observable();
  9020. this.onContextRestoredObservable = new BABYLON.Observable();
  9021. this._contextWasLost = false;
  9022. this._doNotHandleContextLost = false;
  9023. // FPS
  9024. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9025. this._fps = 60;
  9026. this._deltaTime = 0;
  9027. /**
  9028. * Turn this value on if you want to pause FPS computation when in background
  9029. */
  9030. this.disablePerformanceMonitorInBackground = false;
  9031. // States
  9032. this._depthCullingState = new BABYLON._DepthCullingState();
  9033. this._stencilState = new BABYLON._StencilState();
  9034. this._alphaState = new BABYLON._AlphaState();
  9035. this._alphaMode = Engine.ALPHA_DISABLE;
  9036. // Cache
  9037. this._internalTexturesCache = new Array();
  9038. this._activeChannel = 0;
  9039. this._currentTextureChannel = -1;
  9040. this._boundTexturesCache = {};
  9041. this._compiledEffects = {};
  9042. this._vertexAttribArraysEnabled = [];
  9043. this._uintIndicesCurrentlySet = false;
  9044. this._currentBoundBuffer = new Array();
  9045. this._currentBufferPointers = new Array();
  9046. this._currentInstanceLocations = new Array();
  9047. this._currentInstanceBuffers = new Array();
  9048. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9049. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9050. this._vaoRecordInProgress = false;
  9051. this._mustWipeVertexAttributes = false;
  9052. this._nextFreeTextureSlots = new Array();
  9053. this._maxSimultaneousTextures = 0;
  9054. this._activeRequests = new Array();
  9055. // Hardware supported Compressed Textures
  9056. this._texturesSupported = new Array();
  9057. this._onVRFullScreenTriggered = function () {
  9058. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9059. //get the old size before we change
  9060. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9061. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9062. //get the width and height, change the render size
  9063. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9064. _this.setHardwareScalingLevel(1);
  9065. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9066. }
  9067. else {
  9068. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9069. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9070. }
  9071. };
  9072. this._boundUniforms = {};
  9073. var canvas = null;
  9074. Engine.Instances.push(this);
  9075. if (!canvasOrContext) {
  9076. return;
  9077. }
  9078. options = options || {};
  9079. if (canvasOrContext.getContext) {
  9080. canvas = canvasOrContext;
  9081. this._renderingCanvas = canvas;
  9082. if (antialias != null) {
  9083. options.antialias = antialias;
  9084. }
  9085. if (options.deterministicLockstep === undefined) {
  9086. options.deterministicLockstep = false;
  9087. }
  9088. if (options.lockstepMaxSteps === undefined) {
  9089. options.lockstepMaxSteps = 4;
  9090. }
  9091. if (options.preserveDrawingBuffer === undefined) {
  9092. options.preserveDrawingBuffer = false;
  9093. }
  9094. if (options.audioEngine === undefined) {
  9095. options.audioEngine = true;
  9096. }
  9097. if (options.stencil === undefined) {
  9098. options.stencil = true;
  9099. }
  9100. this._deterministicLockstep = options.deterministicLockstep;
  9101. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9102. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9103. // Exceptions
  9104. if (navigator && navigator.userAgent) {
  9105. var ua = navigator.userAgent;
  9106. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9107. var exception = _a[_i];
  9108. var key = exception.key;
  9109. var targets = exception.targets;
  9110. if (ua.indexOf(key) > -1) {
  9111. if (exception.capture && exception.captureConstraint) {
  9112. var capture = exception.capture;
  9113. var constraint = exception.captureConstraint;
  9114. var regex = new RegExp(capture);
  9115. var matches = regex.exec(ua);
  9116. if (matches && matches.length > 0) {
  9117. var capturedValue = parseInt(matches[matches.length - 1]);
  9118. if (capturedValue >= constraint) {
  9119. continue;
  9120. }
  9121. }
  9122. }
  9123. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9124. var target = targets_1[_b];
  9125. switch (target) {
  9126. case "uniformBuffer":
  9127. this.disableUniformBuffers = true;
  9128. break;
  9129. case "textureBindingOptimization":
  9130. this.disableTextureBindingOptimization = true;
  9131. break;
  9132. }
  9133. }
  9134. break;
  9135. }
  9136. }
  9137. }
  9138. // GL
  9139. if (!options.disableWebGL2Support) {
  9140. try {
  9141. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9142. if (this._gl) {
  9143. this._webGLVersion = 2.0;
  9144. }
  9145. }
  9146. catch (e) {
  9147. // Do nothing
  9148. }
  9149. }
  9150. if (!this._gl) {
  9151. if (!canvas) {
  9152. throw new Error("The provided canvas is null or undefined.");
  9153. }
  9154. try {
  9155. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9156. }
  9157. catch (e) {
  9158. throw new Error("WebGL not supported");
  9159. }
  9160. }
  9161. if (!this._gl) {
  9162. throw new Error("WebGL not supported");
  9163. }
  9164. this._onCanvasFocus = function () {
  9165. _this.onCanvasFocusObservable.notifyObservers(_this);
  9166. };
  9167. this._onCanvasBlur = function () {
  9168. _this.onCanvasBlurObservable.notifyObservers(_this);
  9169. };
  9170. canvas.addEventListener("focus", this._onCanvasFocus);
  9171. canvas.addEventListener("blur", this._onCanvasBlur);
  9172. this._onBlur = function () {
  9173. if (_this.disablePerformanceMonitorInBackground) {
  9174. _this._performanceMonitor.disable();
  9175. }
  9176. _this._windowIsBackground = true;
  9177. };
  9178. this._onFocus = function () {
  9179. if (_this.disablePerformanceMonitorInBackground) {
  9180. _this._performanceMonitor.enable();
  9181. }
  9182. _this._windowIsBackground = false;
  9183. };
  9184. this._onCanvasPointerOut = function () {
  9185. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9186. };
  9187. window.addEventListener("blur", this._onBlur);
  9188. window.addEventListener("focus", this._onFocus);
  9189. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9190. // Context lost
  9191. if (!this._doNotHandleContextLost) {
  9192. this._onContextLost = function (evt) {
  9193. evt.preventDefault();
  9194. _this._contextWasLost = true;
  9195. BABYLON.Tools.Warn("WebGL context lost.");
  9196. _this.onContextLostObservable.notifyObservers(_this);
  9197. };
  9198. this._onContextRestored = function (evt) {
  9199. // Adding a timeout to avoid race condition at browser level
  9200. setTimeout(function () {
  9201. // Rebuild gl context
  9202. _this._initGLContext();
  9203. // Rebuild effects
  9204. _this._rebuildEffects();
  9205. // Rebuild textures
  9206. _this._rebuildInternalTextures();
  9207. // Rebuild buffers
  9208. _this._rebuildBuffers();
  9209. // Cache
  9210. _this.wipeCaches(true);
  9211. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9212. _this.onContextRestoredObservable.notifyObservers(_this);
  9213. _this._contextWasLost = false;
  9214. }, 0);
  9215. };
  9216. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9217. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9218. }
  9219. }
  9220. else {
  9221. this._gl = canvasOrContext;
  9222. this._renderingCanvas = this._gl.canvas;
  9223. if (this._gl.renderbufferStorageMultisample) {
  9224. this._webGLVersion = 2.0;
  9225. }
  9226. options.stencil = this._gl.getContextAttributes().stencil;
  9227. }
  9228. // Viewport
  9229. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9230. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9231. this.resize();
  9232. this._isStencilEnable = options.stencil ? true : false;
  9233. this._initGLContext();
  9234. if (canvas) {
  9235. // Fullscreen
  9236. this._onFullscreenChange = function () {
  9237. if (document.fullscreen !== undefined) {
  9238. _this.isFullscreen = document.fullscreen;
  9239. }
  9240. else if (document.mozFullScreen !== undefined) {
  9241. _this.isFullscreen = document.mozFullScreen;
  9242. }
  9243. else if (document.webkitIsFullScreen !== undefined) {
  9244. _this.isFullscreen = document.webkitIsFullScreen;
  9245. }
  9246. else if (document.msIsFullScreen !== undefined) {
  9247. _this.isFullscreen = document.msIsFullScreen;
  9248. }
  9249. // Pointer lock
  9250. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9251. canvas.requestPointerLock = canvas.requestPointerLock ||
  9252. canvas.msRequestPointerLock ||
  9253. canvas.mozRequestPointerLock ||
  9254. canvas.webkitRequestPointerLock;
  9255. if (canvas.requestPointerLock) {
  9256. canvas.requestPointerLock();
  9257. }
  9258. }
  9259. };
  9260. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9261. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9262. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9263. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9264. // Pointer lock
  9265. this._onPointerLockChange = function () {
  9266. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9267. document.webkitPointerLockElement === canvas ||
  9268. document.msPointerLockElement === canvas ||
  9269. document.pointerLockElement === canvas);
  9270. };
  9271. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9272. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9273. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9274. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9275. this._onVRDisplayPointerRestricted = function () {
  9276. if (canvas) {
  9277. canvas.requestPointerLock();
  9278. }
  9279. };
  9280. this._onVRDisplayPointerUnrestricted = function () {
  9281. document.exitPointerLock();
  9282. };
  9283. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9284. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9285. }
  9286. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9287. Engine.audioEngine = new BABYLON.AudioEngine();
  9288. }
  9289. // Prepare buffer pointers
  9290. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9291. this._currentBufferPointers[i] = new BufferPointer();
  9292. }
  9293. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9294. // Load WebVR Devices
  9295. if (options.autoEnableWebVR) {
  9296. this.initWebVR();
  9297. }
  9298. // Detect if we are running on a faulty buggy OS.
  9299. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9300. // Detect if we are running on a faulty buggy desktop OS.
  9301. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9302. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9303. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9304. }
  9305. Object.defineProperty(Engine, "LastCreatedEngine", {
  9306. get: function () {
  9307. if (Engine.Instances.length === 0) {
  9308. return null;
  9309. }
  9310. return Engine.Instances[Engine.Instances.length - 1];
  9311. },
  9312. enumerable: true,
  9313. configurable: true
  9314. });
  9315. Object.defineProperty(Engine, "LastCreatedScene", {
  9316. get: function () {
  9317. var lastCreatedEngine = Engine.LastCreatedEngine;
  9318. if (!lastCreatedEngine) {
  9319. return null;
  9320. }
  9321. if (lastCreatedEngine.scenes.length === 0) {
  9322. return null;
  9323. }
  9324. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9325. },
  9326. enumerable: true,
  9327. configurable: true
  9328. });
  9329. /**
  9330. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9331. */
  9332. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9333. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9334. var engine = Engine.Instances[engineIndex];
  9335. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9336. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9337. }
  9338. }
  9339. };
  9340. Object.defineProperty(Engine, "NEVER", {
  9341. get: function () {
  9342. return Engine._NEVER;
  9343. },
  9344. enumerable: true,
  9345. configurable: true
  9346. });
  9347. Object.defineProperty(Engine, "ALWAYS", {
  9348. get: function () {
  9349. return Engine._ALWAYS;
  9350. },
  9351. enumerable: true,
  9352. configurable: true
  9353. });
  9354. Object.defineProperty(Engine, "LESS", {
  9355. get: function () {
  9356. return Engine._LESS;
  9357. },
  9358. enumerable: true,
  9359. configurable: true
  9360. });
  9361. Object.defineProperty(Engine, "EQUAL", {
  9362. get: function () {
  9363. return Engine._EQUAL;
  9364. },
  9365. enumerable: true,
  9366. configurable: true
  9367. });
  9368. Object.defineProperty(Engine, "LEQUAL", {
  9369. get: function () {
  9370. return Engine._LEQUAL;
  9371. },
  9372. enumerable: true,
  9373. configurable: true
  9374. });
  9375. Object.defineProperty(Engine, "GREATER", {
  9376. get: function () {
  9377. return Engine._GREATER;
  9378. },
  9379. enumerable: true,
  9380. configurable: true
  9381. });
  9382. Object.defineProperty(Engine, "GEQUAL", {
  9383. get: function () {
  9384. return Engine._GEQUAL;
  9385. },
  9386. enumerable: true,
  9387. configurable: true
  9388. });
  9389. Object.defineProperty(Engine, "NOTEQUAL", {
  9390. get: function () {
  9391. return Engine._NOTEQUAL;
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(Engine, "KEEP", {
  9397. get: function () {
  9398. return Engine._KEEP;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(Engine, "REPLACE", {
  9404. get: function () {
  9405. return Engine._REPLACE;
  9406. },
  9407. enumerable: true,
  9408. configurable: true
  9409. });
  9410. Object.defineProperty(Engine, "INCR", {
  9411. get: function () {
  9412. return Engine._INCR;
  9413. },
  9414. enumerable: true,
  9415. configurable: true
  9416. });
  9417. Object.defineProperty(Engine, "DECR", {
  9418. get: function () {
  9419. return Engine._DECR;
  9420. },
  9421. enumerable: true,
  9422. configurable: true
  9423. });
  9424. Object.defineProperty(Engine, "INVERT", {
  9425. get: function () {
  9426. return Engine._INVERT;
  9427. },
  9428. enumerable: true,
  9429. configurable: true
  9430. });
  9431. Object.defineProperty(Engine, "INCR_WRAP", {
  9432. get: function () {
  9433. return Engine._INCR_WRAP;
  9434. },
  9435. enumerable: true,
  9436. configurable: true
  9437. });
  9438. Object.defineProperty(Engine, "DECR_WRAP", {
  9439. get: function () {
  9440. return Engine._DECR_WRAP;
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9446. get: function () {
  9447. return Engine._ALPHA_DISABLE;
  9448. },
  9449. enumerable: true,
  9450. configurable: true
  9451. });
  9452. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9453. get: function () {
  9454. return Engine._ALPHA_ONEONE;
  9455. },
  9456. enumerable: true,
  9457. configurable: true
  9458. });
  9459. Object.defineProperty(Engine, "ALPHA_ADD", {
  9460. get: function () {
  9461. return Engine._ALPHA_ADD;
  9462. },
  9463. enumerable: true,
  9464. configurable: true
  9465. });
  9466. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9467. get: function () {
  9468. return Engine._ALPHA_COMBINE;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9474. get: function () {
  9475. return Engine._ALPHA_SUBTRACT;
  9476. },
  9477. enumerable: true,
  9478. configurable: true
  9479. });
  9480. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9481. get: function () {
  9482. return Engine._ALPHA_MULTIPLY;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9488. get: function () {
  9489. return Engine._ALPHA_MAXIMIZED;
  9490. },
  9491. enumerable: true,
  9492. configurable: true
  9493. });
  9494. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9495. get: function () {
  9496. return Engine._ALPHA_PREMULTIPLIED;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9502. get: function () {
  9503. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9504. },
  9505. enumerable: true,
  9506. configurable: true
  9507. });
  9508. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9509. get: function () {
  9510. return Engine._ALPHA_INTERPOLATE;
  9511. },
  9512. enumerable: true,
  9513. configurable: true
  9514. });
  9515. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9516. get: function () {
  9517. return Engine._ALPHA_SCREENMODE;
  9518. },
  9519. enumerable: true,
  9520. configurable: true
  9521. });
  9522. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9523. get: function () {
  9524. return Engine._DELAYLOADSTATE_NONE;
  9525. },
  9526. enumerable: true,
  9527. configurable: true
  9528. });
  9529. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9530. get: function () {
  9531. return Engine._DELAYLOADSTATE_LOADED;
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9537. get: function () {
  9538. return Engine._DELAYLOADSTATE_LOADING;
  9539. },
  9540. enumerable: true,
  9541. configurable: true
  9542. });
  9543. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9544. get: function () {
  9545. return Engine._DELAYLOADSTATE_NOTLOADED;
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9551. get: function () {
  9552. return Engine._TEXTUREFORMAT_ALPHA;
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9558. get: function () {
  9559. return Engine._TEXTUREFORMAT_LUMINANCE;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9565. get: function () {
  9566. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9567. },
  9568. enumerable: true,
  9569. configurable: true
  9570. });
  9571. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9572. get: function () {
  9573. return Engine._TEXTUREFORMAT_RGB;
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9579. get: function () {
  9580. return Engine._TEXTUREFORMAT_RGBA;
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9586. get: function () {
  9587. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9593. get: function () {
  9594. return Engine._TEXTURETYPE_FLOAT;
  9595. },
  9596. enumerable: true,
  9597. configurable: true
  9598. });
  9599. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9600. get: function () {
  9601. return Engine._TEXTURETYPE_HALF_FLOAT;
  9602. },
  9603. enumerable: true,
  9604. configurable: true
  9605. });
  9606. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9607. get: function () {
  9608. return Engine._SCALEMODE_FLOOR;
  9609. },
  9610. enumerable: true,
  9611. configurable: true
  9612. });
  9613. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9614. get: function () {
  9615. return Engine._SCALEMODE_NEAREST;
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9621. get: function () {
  9622. return Engine._SCALEMODE_CEILING;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. Object.defineProperty(Engine, "Version", {
  9628. get: function () {
  9629. return "3.2.0-alpha5";
  9630. },
  9631. enumerable: true,
  9632. configurable: true
  9633. });
  9634. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9635. get: function () {
  9636. return this._vrExclusivePointerMode;
  9637. },
  9638. enumerable: true,
  9639. configurable: true
  9640. });
  9641. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9642. get: function () {
  9643. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9644. },
  9645. enumerable: true,
  9646. configurable: true
  9647. });
  9648. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9649. get: function () {
  9650. return this._webGLVersion < 2 || this.forcePOTTextures;
  9651. },
  9652. enumerable: true,
  9653. configurable: true
  9654. });
  9655. Object.defineProperty(Engine.prototype, "badOS", {
  9656. get: function () {
  9657. return this._badOS;
  9658. },
  9659. enumerable: true,
  9660. configurable: true
  9661. });
  9662. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9663. get: function () {
  9664. return this._badDesktopOS;
  9665. },
  9666. enumerable: true,
  9667. configurable: true
  9668. });
  9669. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9670. get: function () {
  9671. return this._performanceMonitor;
  9672. },
  9673. enumerable: true,
  9674. configurable: true
  9675. });
  9676. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9677. get: function () {
  9678. return this._texturesSupported;
  9679. },
  9680. enumerable: true,
  9681. configurable: true
  9682. });
  9683. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9684. get: function () {
  9685. return this._textureFormatInUse;
  9686. },
  9687. enumerable: true,
  9688. configurable: true
  9689. });
  9690. Object.defineProperty(Engine.prototype, "currentViewport", {
  9691. get: function () {
  9692. return this._cachedViewport;
  9693. },
  9694. enumerable: true,
  9695. configurable: true
  9696. });
  9697. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9698. // Empty texture
  9699. get: function () {
  9700. if (!this._emptyTexture) {
  9701. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9702. }
  9703. return this._emptyTexture;
  9704. },
  9705. enumerable: true,
  9706. configurable: true
  9707. });
  9708. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9709. get: function () {
  9710. if (!this._emptyTexture3D) {
  9711. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9712. }
  9713. return this._emptyTexture3D;
  9714. },
  9715. enumerable: true,
  9716. configurable: true
  9717. });
  9718. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9719. get: function () {
  9720. if (!this._emptyCubeTexture) {
  9721. var faceData = new Uint8Array(4);
  9722. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9723. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9724. }
  9725. return this._emptyCubeTexture;
  9726. },
  9727. enumerable: true,
  9728. configurable: true
  9729. });
  9730. Engine.prototype._rebuildInternalTextures = function () {
  9731. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9732. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9733. var internalTexture = currentState_1[_i];
  9734. internalTexture._rebuild();
  9735. }
  9736. };
  9737. Engine.prototype._rebuildEffects = function () {
  9738. for (var key in this._compiledEffects) {
  9739. var effect = this._compiledEffects[key];
  9740. effect._prepareEffect();
  9741. }
  9742. BABYLON.Effect.ResetCache();
  9743. };
  9744. Engine.prototype._rebuildBuffers = function () {
  9745. // Index / Vertex
  9746. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9747. var scene = _a[_i];
  9748. scene.resetCachedMaterial();
  9749. scene._rebuildGeometries();
  9750. scene._rebuildTextures();
  9751. }
  9752. // Uniforms
  9753. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9754. var uniformBuffer = _c[_b];
  9755. uniformBuffer._rebuild();
  9756. }
  9757. };
  9758. Engine.prototype._initGLContext = function () {
  9759. // Caps
  9760. this._caps = new EngineCapabilities();
  9761. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9762. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9763. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9764. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9765. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9766. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9767. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9768. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9769. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9770. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9771. // Infos
  9772. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9773. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9774. if (rendererInfo != null) {
  9775. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9776. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9777. }
  9778. if (!this._glVendor) {
  9779. this._glVendor = "Unknown vendor";
  9780. }
  9781. if (!this._glRenderer) {
  9782. this._glRenderer = "Unknown renderer";
  9783. }
  9784. // Constants
  9785. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9786. if (this._gl.RGBA16F !== 0x881A) {
  9787. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9788. }
  9789. if (this._gl.RGBA32F !== 0x8814) {
  9790. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9791. }
  9792. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9793. this._gl.DEPTH24_STENCIL8 = 35056;
  9794. }
  9795. // Extensions
  9796. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9797. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9798. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9799. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9800. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9801. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9802. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9803. 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');
  9804. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9805. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9806. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9807. this._caps.highPrecisionShaderSupported = true;
  9808. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9809. if (this._caps.timerQuery) {
  9810. if (this._webGLVersion === 1) {
  9811. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9812. }
  9813. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9814. }
  9815. // Checks if some of the format renders first to allow the use of webgl inspector.
  9816. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9817. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9818. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9819. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9820. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9821. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9822. if (this._webGLVersion > 1) {
  9823. this._gl.HALF_FLOAT_OES = 0x140B;
  9824. }
  9825. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9826. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9827. // Draw buffers
  9828. if (this._webGLVersion > 1) {
  9829. this._caps.drawBuffersExtension = true;
  9830. }
  9831. else {
  9832. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9833. if (drawBuffersExtension !== null) {
  9834. this._caps.drawBuffersExtension = true;
  9835. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9836. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9837. for (var i = 0; i < 16; i++) {
  9838. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9839. }
  9840. }
  9841. else {
  9842. this._caps.drawBuffersExtension = false;
  9843. }
  9844. }
  9845. // Depth Texture
  9846. if (this._webGLVersion > 1) {
  9847. this._caps.depthTextureExtension = true;
  9848. }
  9849. else {
  9850. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9851. if (depthTextureExtension != null) {
  9852. this._caps.depthTextureExtension = true;
  9853. }
  9854. }
  9855. // Vertex array object
  9856. if (this._webGLVersion > 1) {
  9857. this._caps.vertexArrayObject = true;
  9858. }
  9859. else {
  9860. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9861. if (vertexArrayObjectExtension != null) {
  9862. this._caps.vertexArrayObject = true;
  9863. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9864. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9865. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9866. }
  9867. else {
  9868. this._caps.vertexArrayObject = false;
  9869. }
  9870. }
  9871. // Instances count
  9872. if (this._webGLVersion > 1) {
  9873. this._caps.instancedArrays = true;
  9874. }
  9875. else {
  9876. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9877. if (instanceExtension != null) {
  9878. this._caps.instancedArrays = true;
  9879. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9880. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9881. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9882. }
  9883. else {
  9884. this._caps.instancedArrays = false;
  9885. }
  9886. }
  9887. // Intelligently add supported compressed formats in order to check for.
  9888. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9889. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9890. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9891. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9892. if (this._caps.astc)
  9893. this.texturesSupported.push('-astc.ktx');
  9894. if (this._caps.s3tc)
  9895. this.texturesSupported.push('-dxt.ktx');
  9896. if (this._caps.pvrtc)
  9897. this.texturesSupported.push('-pvrtc.ktx');
  9898. if (this._caps.etc2)
  9899. this.texturesSupported.push('-etc2.ktx');
  9900. if (this._caps.etc1)
  9901. this.texturesSupported.push('-etc1.ktx');
  9902. if (this._gl.getShaderPrecisionFormat) {
  9903. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9904. if (highp) {
  9905. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9906. }
  9907. }
  9908. // Depth buffer
  9909. this.setDepthBuffer(true);
  9910. this.setDepthFunctionToLessOrEqual();
  9911. this.setDepthWrite(true);
  9912. // Texture maps
  9913. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9914. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9915. this._nextFreeTextureSlots.push(slot);
  9916. }
  9917. };
  9918. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9919. get: function () {
  9920. return this._webGLVersion;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9926. /**
  9927. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9928. */
  9929. get: function () {
  9930. return this._isStencilEnable;
  9931. },
  9932. enumerable: true,
  9933. configurable: true
  9934. });
  9935. Engine.prototype._prepareWorkingCanvas = function () {
  9936. if (this._workingCanvas) {
  9937. return;
  9938. }
  9939. this._workingCanvas = document.createElement("canvas");
  9940. var context = this._workingCanvas.getContext("2d");
  9941. if (context) {
  9942. this._workingContext = context;
  9943. }
  9944. };
  9945. Engine.prototype.resetTextureCache = function () {
  9946. for (var key in this._boundTexturesCache) {
  9947. var boundTexture = this._boundTexturesCache[key];
  9948. if (boundTexture) {
  9949. this._removeDesignatedSlot(boundTexture);
  9950. }
  9951. this._boundTexturesCache[key] = null;
  9952. }
  9953. this._nextFreeTextureSlots = [];
  9954. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9955. this._nextFreeTextureSlots.push(slot);
  9956. }
  9957. this._currentTextureChannel = -1;
  9958. };
  9959. Engine.prototype.isDeterministicLockStep = function () {
  9960. return this._deterministicLockstep;
  9961. };
  9962. Engine.prototype.getLockstepMaxSteps = function () {
  9963. return this._lockstepMaxSteps;
  9964. };
  9965. Engine.prototype.getGlInfo = function () {
  9966. return {
  9967. vendor: this._glVendor,
  9968. renderer: this._glRenderer,
  9969. version: this._glVersion
  9970. };
  9971. };
  9972. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9973. if (useScreen === void 0) { useScreen = false; }
  9974. var viewport = camera.viewport;
  9975. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9976. };
  9977. Engine.prototype.getRenderWidth = function (useScreen) {
  9978. if (useScreen === void 0) { useScreen = false; }
  9979. if (!useScreen && this._currentRenderTarget) {
  9980. return this._currentRenderTarget.width;
  9981. }
  9982. return this._gl.drawingBufferWidth;
  9983. };
  9984. Engine.prototype.getRenderHeight = function (useScreen) {
  9985. if (useScreen === void 0) { useScreen = false; }
  9986. if (!useScreen && this._currentRenderTarget) {
  9987. return this._currentRenderTarget.height;
  9988. }
  9989. return this._gl.drawingBufferHeight;
  9990. };
  9991. Engine.prototype.getRenderingCanvas = function () {
  9992. return this._renderingCanvas;
  9993. };
  9994. Engine.prototype.getRenderingCanvasClientRect = function () {
  9995. if (!this._renderingCanvas) {
  9996. return null;
  9997. }
  9998. return this._renderingCanvas.getBoundingClientRect();
  9999. };
  10000. Engine.prototype.setHardwareScalingLevel = function (level) {
  10001. this._hardwareScalingLevel = level;
  10002. this.resize();
  10003. };
  10004. Engine.prototype.getHardwareScalingLevel = function () {
  10005. return this._hardwareScalingLevel;
  10006. };
  10007. Engine.prototype.getLoadedTexturesCache = function () {
  10008. return this._internalTexturesCache;
  10009. };
  10010. Engine.prototype.getCaps = function () {
  10011. return this._caps;
  10012. };
  10013. Object.defineProperty(Engine.prototype, "drawCalls", {
  10014. /** The number of draw calls submitted last frame */
  10015. get: function () {
  10016. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10017. return 0;
  10018. },
  10019. enumerable: true,
  10020. configurable: true
  10021. });
  10022. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10023. get: function () {
  10024. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10025. return null;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Engine.prototype.getDepthFunction = function () {
  10031. return this._depthCullingState.depthFunc;
  10032. };
  10033. Engine.prototype.setDepthFunction = function (depthFunc) {
  10034. this._depthCullingState.depthFunc = depthFunc;
  10035. };
  10036. Engine.prototype.setDepthFunctionToGreater = function () {
  10037. this._depthCullingState.depthFunc = this._gl.GREATER;
  10038. };
  10039. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10040. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10041. };
  10042. Engine.prototype.setDepthFunctionToLess = function () {
  10043. this._depthCullingState.depthFunc = this._gl.LESS;
  10044. };
  10045. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10046. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10047. };
  10048. Engine.prototype.getStencilBuffer = function () {
  10049. return this._stencilState.stencilTest;
  10050. };
  10051. Engine.prototype.setStencilBuffer = function (enable) {
  10052. this._stencilState.stencilTest = enable;
  10053. };
  10054. Engine.prototype.getStencilMask = function () {
  10055. return this._stencilState.stencilMask;
  10056. };
  10057. Engine.prototype.setStencilMask = function (mask) {
  10058. this._stencilState.stencilMask = mask;
  10059. };
  10060. Engine.prototype.getStencilFunction = function () {
  10061. return this._stencilState.stencilFunc;
  10062. };
  10063. Engine.prototype.getStencilFunctionReference = function () {
  10064. return this._stencilState.stencilFuncRef;
  10065. };
  10066. Engine.prototype.getStencilFunctionMask = function () {
  10067. return this._stencilState.stencilFuncMask;
  10068. };
  10069. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10070. this._stencilState.stencilFunc = stencilFunc;
  10071. };
  10072. Engine.prototype.setStencilFunctionReference = function (reference) {
  10073. this._stencilState.stencilFuncRef = reference;
  10074. };
  10075. Engine.prototype.setStencilFunctionMask = function (mask) {
  10076. this._stencilState.stencilFuncMask = mask;
  10077. };
  10078. Engine.prototype.getStencilOperationFail = function () {
  10079. return this._stencilState.stencilOpStencilFail;
  10080. };
  10081. Engine.prototype.getStencilOperationDepthFail = function () {
  10082. return this._stencilState.stencilOpDepthFail;
  10083. };
  10084. Engine.prototype.getStencilOperationPass = function () {
  10085. return this._stencilState.stencilOpStencilDepthPass;
  10086. };
  10087. Engine.prototype.setStencilOperationFail = function (operation) {
  10088. this._stencilState.stencilOpStencilFail = operation;
  10089. };
  10090. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10091. this._stencilState.stencilOpDepthFail = operation;
  10092. };
  10093. Engine.prototype.setStencilOperationPass = function (operation) {
  10094. this._stencilState.stencilOpStencilDepthPass = operation;
  10095. };
  10096. Engine.prototype.setDitheringState = function (value) {
  10097. if (value) {
  10098. this._gl.enable(this._gl.DITHER);
  10099. }
  10100. else {
  10101. this._gl.disable(this._gl.DITHER);
  10102. }
  10103. };
  10104. Engine.prototype.setRasterizerState = function (value) {
  10105. if (value) {
  10106. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10107. }
  10108. else {
  10109. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10110. }
  10111. };
  10112. /**
  10113. * stop executing a render loop function and remove it from the execution array
  10114. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10115. */
  10116. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10117. if (!renderFunction) {
  10118. this._activeRenderLoops = [];
  10119. return;
  10120. }
  10121. var index = this._activeRenderLoops.indexOf(renderFunction);
  10122. if (index >= 0) {
  10123. this._activeRenderLoops.splice(index, 1);
  10124. }
  10125. };
  10126. Engine.prototype._renderLoop = function () {
  10127. if (!this._contextWasLost) {
  10128. var shouldRender = true;
  10129. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10130. shouldRender = false;
  10131. }
  10132. if (shouldRender) {
  10133. // Start new frame
  10134. this.beginFrame();
  10135. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10136. var renderFunction = this._activeRenderLoops[index];
  10137. renderFunction();
  10138. }
  10139. // Present
  10140. this.endFrame();
  10141. }
  10142. }
  10143. if (this._activeRenderLoops.length > 0) {
  10144. // Register new frame
  10145. var requester = null;
  10146. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10147. requester = this._vrDisplay;
  10148. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10149. }
  10150. else {
  10151. this._renderingQueueLaunched = false;
  10152. }
  10153. };
  10154. /**
  10155. * Register and execute a render loop. The engine can have more than one render function.
  10156. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10157. * @example
  10158. * engine.runRenderLoop(function () {
  10159. * scene.render()
  10160. * })
  10161. */
  10162. Engine.prototype.runRenderLoop = function (renderFunction) {
  10163. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10164. return;
  10165. }
  10166. this._activeRenderLoops.push(renderFunction);
  10167. if (!this._renderingQueueLaunched) {
  10168. this._renderingQueueLaunched = true;
  10169. this._bindedRenderFunction = this._renderLoop.bind(this);
  10170. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10171. }
  10172. };
  10173. /**
  10174. * Toggle full screen mode.
  10175. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10176. * @param {any} options - an options object to be sent to the requestFullscreen function
  10177. */
  10178. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10179. if (this.isFullscreen) {
  10180. BABYLON.Tools.ExitFullscreen();
  10181. }
  10182. else {
  10183. this._pointerLockRequested = requestPointerLock;
  10184. if (this._renderingCanvas) {
  10185. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10186. }
  10187. }
  10188. };
  10189. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10190. if (stencil === void 0) { stencil = false; }
  10191. this.applyStates();
  10192. var mode = 0;
  10193. if (backBuffer && color) {
  10194. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10195. mode |= this._gl.COLOR_BUFFER_BIT;
  10196. }
  10197. if (depth) {
  10198. this._gl.clearDepth(1.0);
  10199. mode |= this._gl.DEPTH_BUFFER_BIT;
  10200. }
  10201. if (stencil) {
  10202. this._gl.clearStencil(0);
  10203. mode |= this._gl.STENCIL_BUFFER_BIT;
  10204. }
  10205. this._gl.clear(mode);
  10206. };
  10207. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10208. var gl = this._gl;
  10209. // Save state
  10210. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10211. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10212. // Change state
  10213. gl.enable(gl.SCISSOR_TEST);
  10214. gl.scissor(x, y, width, height);
  10215. // Clear
  10216. this.clear(clearColor, true, true, true);
  10217. // Restore state
  10218. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10219. if (curScissor === true) {
  10220. gl.enable(gl.SCISSOR_TEST);
  10221. }
  10222. else {
  10223. gl.disable(gl.SCISSOR_TEST);
  10224. }
  10225. };
  10226. /**
  10227. * Set the WebGL's viewport
  10228. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10229. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10230. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10231. */
  10232. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10233. var width = requiredWidth || this.getRenderWidth();
  10234. var height = requiredHeight || this.getRenderHeight();
  10235. var x = viewport.x || 0;
  10236. var y = viewport.y || 0;
  10237. this._cachedViewport = viewport;
  10238. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10239. };
  10240. /**
  10241. * Directly set the WebGL Viewport
  10242. * The x, y, width & height are directly passed to the WebGL call
  10243. * @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.
  10244. */
  10245. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10246. var currentViewport = this._cachedViewport;
  10247. this._cachedViewport = null;
  10248. this._gl.viewport(x, y, width, height);
  10249. return currentViewport;
  10250. };
  10251. Engine.prototype.beginFrame = function () {
  10252. this.onBeginFrameObservable.notifyObservers(this);
  10253. this._measureFps();
  10254. };
  10255. Engine.prototype.endFrame = function () {
  10256. //force a flush in case we are using a bad OS.
  10257. if (this._badOS) {
  10258. this.flushFramebuffer();
  10259. }
  10260. //submit frame to the vr device, if enabled
  10261. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10262. // TODO: We should only submit the frame if we read frameData successfully.
  10263. this._vrDisplay.submitFrame();
  10264. }
  10265. this.onEndFrameObservable.notifyObservers(this);
  10266. };
  10267. /**
  10268. * resize the view according to the canvas' size.
  10269. * @example
  10270. * window.addEventListener("resize", function () {
  10271. * engine.resize();
  10272. * });
  10273. */
  10274. Engine.prototype.resize = function () {
  10275. // We're not resizing the size of the canvas while in VR mode & presenting
  10276. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10277. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10278. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10279. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10280. }
  10281. };
  10282. /**
  10283. * force a specific size of the canvas
  10284. * @param {number} width - the new canvas' width
  10285. * @param {number} height - the new canvas' height
  10286. */
  10287. Engine.prototype.setSize = function (width, height) {
  10288. if (!this._renderingCanvas) {
  10289. return;
  10290. }
  10291. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10292. return;
  10293. }
  10294. this._renderingCanvas.width = width;
  10295. this._renderingCanvas.height = height;
  10296. for (var index = 0; index < this.scenes.length; index++) {
  10297. var scene = this.scenes[index];
  10298. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10299. var cam = scene.cameras[camIndex];
  10300. cam._currentRenderId = 0;
  10301. }
  10302. }
  10303. if (this.onResizeObservable.hasObservers) {
  10304. this.onResizeObservable.notifyObservers(this);
  10305. }
  10306. };
  10307. // WebVR functions
  10308. Engine.prototype.isVRDevicePresent = function () {
  10309. return !!this._vrDisplay;
  10310. };
  10311. Engine.prototype.getVRDevice = function () {
  10312. return this._vrDisplay;
  10313. };
  10314. Engine.prototype.initWebVR = function () {
  10315. var _this = this;
  10316. var notifyObservers = function () {
  10317. var eventArgs = {
  10318. vrDisplay: _this._vrDisplay,
  10319. vrSupported: _this._vrSupported
  10320. };
  10321. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10322. };
  10323. if (!this._onVrDisplayConnect) {
  10324. this._onVrDisplayConnect = function (event) {
  10325. _this._vrDisplay = event.display;
  10326. notifyObservers();
  10327. };
  10328. this._onVrDisplayDisconnect = function () {
  10329. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10330. _this._vrDisplay = undefined;
  10331. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10332. notifyObservers();
  10333. };
  10334. this._onVrDisplayPresentChange = function () {
  10335. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10336. };
  10337. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10338. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10339. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10340. }
  10341. this._getVRDisplays(notifyObservers);
  10342. return this.onVRDisplayChangedObservable;
  10343. };
  10344. Engine.prototype.enableVR = function () {
  10345. var _this = this;
  10346. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10347. var onResolved = function () {
  10348. _this.onVRRequestPresentComplete.notifyObservers(true);
  10349. _this._onVRFullScreenTriggered();
  10350. };
  10351. var onRejected = function () {
  10352. _this.onVRRequestPresentComplete.notifyObservers(false);
  10353. };
  10354. this.onVRRequestPresentStart.notifyObservers(this);
  10355. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10356. }
  10357. };
  10358. Engine.prototype.disableVR = function () {
  10359. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10360. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10361. }
  10362. };
  10363. Engine.prototype._getVRDisplays = function (callback) {
  10364. var _this = this;
  10365. var getWebVRDevices = function (devices) {
  10366. _this._vrSupported = true;
  10367. // note that devices may actually be an empty array. This is fine;
  10368. // we expect this._vrDisplay to be undefined in this case.
  10369. return _this._vrDisplay = devices[0];
  10370. };
  10371. if (navigator.getVRDisplays) {
  10372. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10373. // TODO: System CANNOT support WebVR, despite API presence.
  10374. _this._vrSupported = false;
  10375. callback();
  10376. });
  10377. }
  10378. else {
  10379. // TODO: Browser does not support WebVR
  10380. this._vrDisplay = undefined;
  10381. this._vrSupported = false;
  10382. callback();
  10383. }
  10384. };
  10385. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10386. if (this._currentRenderTarget) {
  10387. this.unBindFramebuffer(this._currentRenderTarget);
  10388. }
  10389. this._currentRenderTarget = texture;
  10390. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10391. var gl = this._gl;
  10392. if (texture.isCube) {
  10393. if (faceIndex === undefined) {
  10394. faceIndex = 0;
  10395. }
  10396. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10397. }
  10398. if (this._cachedViewport && !forceFullscreenViewport) {
  10399. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10400. }
  10401. else {
  10402. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10403. }
  10404. this.wipeCaches();
  10405. };
  10406. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10407. if (this._currentFramebuffer !== framebuffer) {
  10408. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10409. this._currentFramebuffer = framebuffer;
  10410. }
  10411. };
  10412. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10413. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10414. this._currentRenderTarget = null;
  10415. // If MSAA, we need to bitblt back to main texture
  10416. var gl = this._gl;
  10417. if (texture._MSAAFramebuffer) {
  10418. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10419. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10420. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10421. }
  10422. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10423. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10424. gl.generateMipmap(gl.TEXTURE_2D);
  10425. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10426. }
  10427. if (onBeforeUnbind) {
  10428. if (texture._MSAAFramebuffer) {
  10429. // Bind the correct framebuffer
  10430. this.bindUnboundFramebuffer(texture._framebuffer);
  10431. }
  10432. onBeforeUnbind();
  10433. }
  10434. this.bindUnboundFramebuffer(null);
  10435. };
  10436. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10437. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10438. this._currentRenderTarget = null;
  10439. // If MSAA, we need to bitblt back to main texture
  10440. var gl = this._gl;
  10441. if (textures[0]._MSAAFramebuffer) {
  10442. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10443. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10444. var attachments = textures[0]._attachments;
  10445. if (!attachments) {
  10446. attachments = new Array(textures.length);
  10447. textures[0]._attachments = attachments;
  10448. }
  10449. for (var i = 0; i < textures.length; i++) {
  10450. var texture = textures[i];
  10451. for (var j = 0; j < attachments.length; j++) {
  10452. attachments[j] = gl.NONE;
  10453. }
  10454. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10455. gl.readBuffer(attachments[i]);
  10456. gl.drawBuffers(attachments);
  10457. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10458. }
  10459. for (var i = 0; i < attachments.length; i++) {
  10460. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10461. }
  10462. gl.drawBuffers(attachments);
  10463. }
  10464. for (var i = 0; i < textures.length; i++) {
  10465. var texture = textures[i];
  10466. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10467. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10468. gl.generateMipmap(gl.TEXTURE_2D);
  10469. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10470. }
  10471. }
  10472. if (onBeforeUnbind) {
  10473. if (textures[0]._MSAAFramebuffer) {
  10474. // Bind the correct framebuffer
  10475. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10476. }
  10477. onBeforeUnbind();
  10478. }
  10479. this.bindUnboundFramebuffer(null);
  10480. };
  10481. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10482. if (texture.generateMipMaps) {
  10483. var gl = this._gl;
  10484. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10485. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10486. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10487. }
  10488. };
  10489. Engine.prototype.flushFramebuffer = function () {
  10490. this._gl.flush();
  10491. };
  10492. Engine.prototype.restoreDefaultFramebuffer = function () {
  10493. if (this._currentRenderTarget) {
  10494. this.unBindFramebuffer(this._currentRenderTarget);
  10495. }
  10496. else {
  10497. this.bindUnboundFramebuffer(null);
  10498. }
  10499. if (this._cachedViewport) {
  10500. this.setViewport(this._cachedViewport);
  10501. }
  10502. this.wipeCaches();
  10503. };
  10504. // UBOs
  10505. Engine.prototype.createUniformBuffer = function (elements) {
  10506. var ubo = this._gl.createBuffer();
  10507. if (!ubo) {
  10508. throw new Error("Unable to create uniform buffer");
  10509. }
  10510. this.bindUniformBuffer(ubo);
  10511. if (elements instanceof Float32Array) {
  10512. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10513. }
  10514. else {
  10515. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10516. }
  10517. this.bindUniformBuffer(null);
  10518. ubo.references = 1;
  10519. return ubo;
  10520. };
  10521. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10522. var ubo = this._gl.createBuffer();
  10523. if (!ubo) {
  10524. throw new Error("Unable to create dynamic uniform buffer");
  10525. }
  10526. this.bindUniformBuffer(ubo);
  10527. if (elements instanceof Float32Array) {
  10528. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10529. }
  10530. else {
  10531. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10532. }
  10533. this.bindUniformBuffer(null);
  10534. ubo.references = 1;
  10535. return ubo;
  10536. };
  10537. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10538. this.bindUniformBuffer(uniformBuffer);
  10539. if (offset === undefined) {
  10540. offset = 0;
  10541. }
  10542. if (count === undefined) {
  10543. if (elements instanceof Float32Array) {
  10544. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10545. }
  10546. else {
  10547. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10548. }
  10549. }
  10550. else {
  10551. if (elements instanceof Float32Array) {
  10552. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10553. }
  10554. else {
  10555. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10556. }
  10557. }
  10558. this.bindUniformBuffer(null);
  10559. };
  10560. // VBOs
  10561. Engine.prototype._resetVertexBufferBinding = function () {
  10562. this.bindArrayBuffer(null);
  10563. this._cachedVertexBuffers = null;
  10564. };
  10565. Engine.prototype.createVertexBuffer = function (vertices) {
  10566. var vbo = this._gl.createBuffer();
  10567. if (!vbo) {
  10568. throw new Error("Unable to create vertex buffer");
  10569. }
  10570. this.bindArrayBuffer(vbo);
  10571. if (vertices instanceof Float32Array) {
  10572. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10573. }
  10574. else {
  10575. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10576. }
  10577. this._resetVertexBufferBinding();
  10578. vbo.references = 1;
  10579. return vbo;
  10580. };
  10581. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10582. var vbo = this._gl.createBuffer();
  10583. if (!vbo) {
  10584. throw new Error("Unable to create dynamic vertex buffer");
  10585. }
  10586. this.bindArrayBuffer(vbo);
  10587. if (vertices instanceof Float32Array) {
  10588. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10589. }
  10590. else {
  10591. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10592. }
  10593. this._resetVertexBufferBinding();
  10594. vbo.references = 1;
  10595. return vbo;
  10596. };
  10597. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10598. if (offset === void 0) { offset = 0; }
  10599. // Force cache update
  10600. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10601. this.bindIndexBuffer(indexBuffer);
  10602. var arrayBuffer;
  10603. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10604. arrayBuffer = indices;
  10605. }
  10606. else {
  10607. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10608. }
  10609. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10610. this._resetIndexBufferBinding();
  10611. };
  10612. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10613. this.bindArrayBuffer(vertexBuffer);
  10614. if (offset === undefined) {
  10615. offset = 0;
  10616. }
  10617. if (count === undefined) {
  10618. if (vertices instanceof Float32Array) {
  10619. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10620. }
  10621. else {
  10622. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10623. }
  10624. }
  10625. else {
  10626. if (vertices instanceof Float32Array) {
  10627. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10628. }
  10629. else {
  10630. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10631. }
  10632. }
  10633. this._resetVertexBufferBinding();
  10634. };
  10635. Engine.prototype._resetIndexBufferBinding = function () {
  10636. this.bindIndexBuffer(null);
  10637. this._cachedIndexBuffer = null;
  10638. };
  10639. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10640. var vbo = this._gl.createBuffer();
  10641. if (!vbo) {
  10642. throw new Error("Unable to create index buffer");
  10643. }
  10644. this.bindIndexBuffer(vbo);
  10645. // Check for 32 bits indices
  10646. var arrayBuffer;
  10647. var need32Bits = false;
  10648. if (indices instanceof Uint16Array) {
  10649. arrayBuffer = indices;
  10650. }
  10651. else {
  10652. //check 32 bit support
  10653. if (this._caps.uintIndices) {
  10654. if (indices instanceof Uint32Array) {
  10655. arrayBuffer = indices;
  10656. need32Bits = true;
  10657. }
  10658. else {
  10659. //number[] or Int32Array, check if 32 bit is necessary
  10660. for (var index = 0; index < indices.length; index++) {
  10661. if (indices[index] > 65535) {
  10662. need32Bits = true;
  10663. break;
  10664. }
  10665. }
  10666. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10667. }
  10668. }
  10669. else {
  10670. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10671. arrayBuffer = new Uint16Array(indices);
  10672. }
  10673. }
  10674. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10675. this._resetIndexBufferBinding();
  10676. vbo.references = 1;
  10677. vbo.is32Bits = need32Bits;
  10678. return vbo;
  10679. };
  10680. Engine.prototype.bindArrayBuffer = function (buffer) {
  10681. if (!this._vaoRecordInProgress) {
  10682. this._unbindVertexArrayObject();
  10683. }
  10684. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10685. };
  10686. Engine.prototype.bindUniformBuffer = function (buffer) {
  10687. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10688. };
  10689. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10690. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10691. };
  10692. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10693. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10694. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10695. };
  10696. ;
  10697. Engine.prototype.bindIndexBuffer = function (buffer) {
  10698. if (!this._vaoRecordInProgress) {
  10699. this._unbindVertexArrayObject();
  10700. }
  10701. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10702. };
  10703. Engine.prototype.bindBuffer = function (buffer, target) {
  10704. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10705. this._gl.bindBuffer(target, buffer);
  10706. this._currentBoundBuffer[target] = buffer;
  10707. }
  10708. };
  10709. Engine.prototype.updateArrayBuffer = function (data) {
  10710. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10711. };
  10712. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10713. var pointer = this._currentBufferPointers[indx];
  10714. var changed = false;
  10715. if (!pointer.active) {
  10716. changed = true;
  10717. pointer.active = true;
  10718. pointer.index = indx;
  10719. pointer.size = size;
  10720. pointer.type = type;
  10721. pointer.normalized = normalized;
  10722. pointer.stride = stride;
  10723. pointer.offset = offset;
  10724. pointer.buffer = buffer;
  10725. }
  10726. else {
  10727. if (pointer.buffer !== buffer) {
  10728. pointer.buffer = buffer;
  10729. changed = true;
  10730. }
  10731. if (pointer.size !== size) {
  10732. pointer.size = size;
  10733. changed = true;
  10734. }
  10735. if (pointer.type !== type) {
  10736. pointer.type = type;
  10737. changed = true;
  10738. }
  10739. if (pointer.normalized !== normalized) {
  10740. pointer.normalized = normalized;
  10741. changed = true;
  10742. }
  10743. if (pointer.stride !== stride) {
  10744. pointer.stride = stride;
  10745. changed = true;
  10746. }
  10747. if (pointer.offset !== offset) {
  10748. pointer.offset = offset;
  10749. changed = true;
  10750. }
  10751. }
  10752. if (changed || this._vaoRecordInProgress) {
  10753. this.bindArrayBuffer(buffer);
  10754. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10755. }
  10756. };
  10757. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10758. if (indexBuffer == null) {
  10759. return;
  10760. }
  10761. if (this._cachedIndexBuffer !== indexBuffer) {
  10762. this._cachedIndexBuffer = indexBuffer;
  10763. this.bindIndexBuffer(indexBuffer);
  10764. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10765. }
  10766. };
  10767. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10768. var attributes = effect.getAttributesNames();
  10769. if (!this._vaoRecordInProgress) {
  10770. this._unbindVertexArrayObject();
  10771. }
  10772. this.unbindAllAttributes();
  10773. for (var index = 0; index < attributes.length; index++) {
  10774. var order = effect.getAttributeLocation(index);
  10775. if (order >= 0) {
  10776. var vertexBuffer = vertexBuffers[attributes[index]];
  10777. if (!vertexBuffer) {
  10778. continue;
  10779. }
  10780. this._gl.enableVertexAttribArray(order);
  10781. if (!this._vaoRecordInProgress) {
  10782. this._vertexAttribArraysEnabled[order] = true;
  10783. }
  10784. var buffer = vertexBuffer.getBuffer();
  10785. if (buffer) {
  10786. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10787. if (vertexBuffer.getIsInstanced()) {
  10788. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10789. if (!this._vaoRecordInProgress) {
  10790. this._currentInstanceLocations.push(order);
  10791. this._currentInstanceBuffers.push(buffer);
  10792. }
  10793. }
  10794. }
  10795. }
  10796. }
  10797. };
  10798. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10799. var vao = this._gl.createVertexArray();
  10800. this._vaoRecordInProgress = true;
  10801. this._gl.bindVertexArray(vao);
  10802. this._mustWipeVertexAttributes = true;
  10803. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10804. this.bindIndexBuffer(indexBuffer);
  10805. this._vaoRecordInProgress = false;
  10806. this._gl.bindVertexArray(null);
  10807. return vao;
  10808. };
  10809. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10810. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10811. this._cachedVertexArrayObject = vertexArrayObject;
  10812. this._gl.bindVertexArray(vertexArrayObject);
  10813. this._cachedVertexBuffers = null;
  10814. this._cachedIndexBuffer = null;
  10815. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10816. this._mustWipeVertexAttributes = true;
  10817. }
  10818. };
  10819. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10820. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10821. this._cachedVertexBuffers = vertexBuffer;
  10822. this._cachedEffectForVertexBuffers = effect;
  10823. var attributesCount = effect.getAttributesCount();
  10824. this._unbindVertexArrayObject();
  10825. this.unbindAllAttributes();
  10826. var offset = 0;
  10827. for (var index = 0; index < attributesCount; index++) {
  10828. if (index < vertexDeclaration.length) {
  10829. var order = effect.getAttributeLocation(index);
  10830. if (order >= 0) {
  10831. this._gl.enableVertexAttribArray(order);
  10832. this._vertexAttribArraysEnabled[order] = true;
  10833. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10834. }
  10835. offset += vertexDeclaration[index] * 4;
  10836. }
  10837. }
  10838. }
  10839. this._bindIndexBufferWithCache(indexBuffer);
  10840. };
  10841. Engine.prototype._unbindVertexArrayObject = function () {
  10842. if (!this._cachedVertexArrayObject) {
  10843. return;
  10844. }
  10845. this._cachedVertexArrayObject = null;
  10846. this._gl.bindVertexArray(null);
  10847. };
  10848. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10849. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10850. this._cachedVertexBuffers = vertexBuffers;
  10851. this._cachedEffectForVertexBuffers = effect;
  10852. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10853. }
  10854. this._bindIndexBufferWithCache(indexBuffer);
  10855. };
  10856. Engine.prototype.unbindInstanceAttributes = function () {
  10857. var boundBuffer;
  10858. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10859. var instancesBuffer = this._currentInstanceBuffers[i];
  10860. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10861. boundBuffer = instancesBuffer;
  10862. this.bindArrayBuffer(instancesBuffer);
  10863. }
  10864. var offsetLocation = this._currentInstanceLocations[i];
  10865. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10866. }
  10867. this._currentInstanceBuffers.length = 0;
  10868. this._currentInstanceLocations.length = 0;
  10869. };
  10870. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10871. this._gl.deleteVertexArray(vao);
  10872. };
  10873. Engine.prototype._releaseBuffer = function (buffer) {
  10874. buffer.references--;
  10875. if (buffer.references === 0) {
  10876. this._gl.deleteBuffer(buffer);
  10877. return true;
  10878. }
  10879. return false;
  10880. };
  10881. Engine.prototype.createInstancesBuffer = function (capacity) {
  10882. var buffer = this._gl.createBuffer();
  10883. if (!buffer) {
  10884. throw new Error("Unable to create instance buffer");
  10885. }
  10886. buffer.capacity = capacity;
  10887. this.bindArrayBuffer(buffer);
  10888. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10889. return buffer;
  10890. };
  10891. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10892. this._gl.deleteBuffer(buffer);
  10893. };
  10894. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10895. this.bindArrayBuffer(instancesBuffer);
  10896. if (data) {
  10897. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10898. }
  10899. if (offsetLocations[0].index !== undefined) {
  10900. var stride = 0;
  10901. for (var i = 0; i < offsetLocations.length; i++) {
  10902. var ai = offsetLocations[i];
  10903. stride += ai.attributeSize * 4;
  10904. }
  10905. for (var i = 0; i < offsetLocations.length; i++) {
  10906. var ai = offsetLocations[i];
  10907. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10908. this._gl.enableVertexAttribArray(ai.index);
  10909. this._vertexAttribArraysEnabled[ai.index] = true;
  10910. }
  10911. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10912. this._gl.vertexAttribDivisor(ai.index, 1);
  10913. this._currentInstanceLocations.push(ai.index);
  10914. this._currentInstanceBuffers.push(instancesBuffer);
  10915. }
  10916. }
  10917. else {
  10918. for (var index = 0; index < 4; index++) {
  10919. var offsetLocation = offsetLocations[index];
  10920. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10921. this._gl.enableVertexAttribArray(offsetLocation);
  10922. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10923. }
  10924. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10925. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10926. this._currentInstanceLocations.push(offsetLocation);
  10927. this._currentInstanceBuffers.push(instancesBuffer);
  10928. }
  10929. }
  10930. };
  10931. Engine.prototype.applyStates = function () {
  10932. this._depthCullingState.apply(this._gl);
  10933. this._stencilState.apply(this._gl);
  10934. this._alphaState.apply(this._gl);
  10935. };
  10936. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10937. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10938. };
  10939. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10940. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10941. };
  10942. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10943. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10944. };
  10945. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10946. // Apply states
  10947. this.applyStates();
  10948. this._drawCalls.addCount(1, false);
  10949. // Render
  10950. var drawMode = this.DrawMode(fillMode);
  10951. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10952. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10953. if (instancesCount) {
  10954. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10955. }
  10956. else {
  10957. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10958. }
  10959. };
  10960. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10961. // Apply states
  10962. this.applyStates();
  10963. this._drawCalls.addCount(1, false);
  10964. var drawMode = this.DrawMode(fillMode);
  10965. if (instancesCount) {
  10966. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10967. }
  10968. else {
  10969. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10970. }
  10971. };
  10972. Engine.prototype.DrawMode = function (fillMode) {
  10973. switch (fillMode) {
  10974. // Triangle views
  10975. case BABYLON.Material.TriangleFillMode:
  10976. return this._gl.TRIANGLES;
  10977. case BABYLON.Material.PointFillMode:
  10978. return this._gl.POINTS;
  10979. case BABYLON.Material.WireFrameFillMode:
  10980. return this._gl.LINES;
  10981. // Draw modes
  10982. case BABYLON.Material.PointListDrawMode:
  10983. return this._gl.POINTS;
  10984. case BABYLON.Material.LineListDrawMode:
  10985. return this._gl.LINES;
  10986. case BABYLON.Material.LineLoopDrawMode:
  10987. return this._gl.LINE_LOOP;
  10988. case BABYLON.Material.LineStripDrawMode:
  10989. return this._gl.LINE_STRIP;
  10990. case BABYLON.Material.TriangleStripDrawMode:
  10991. return this._gl.TRIANGLE_STRIP;
  10992. case BABYLON.Material.TriangleFanDrawMode:
  10993. return this._gl.TRIANGLE_FAN;
  10994. default:
  10995. return this._gl.TRIANGLES;
  10996. }
  10997. };
  10998. // Shaders
  10999. Engine.prototype._releaseEffect = function (effect) {
  11000. if (this._compiledEffects[effect._key]) {
  11001. delete this._compiledEffects[effect._key];
  11002. this._deleteProgram(effect.getProgram());
  11003. }
  11004. };
  11005. Engine.prototype._deleteProgram = function (program) {
  11006. if (program) {
  11007. program.__SPECTOR_rebuildProgram = null;
  11008. if (program.transformFeedback) {
  11009. this.deleteTransformFeedback(program.transformFeedback);
  11010. program.transformFeedback = null;
  11011. }
  11012. this._gl.deleteProgram(program);
  11013. }
  11014. };
  11015. /**
  11016. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11017. * @param samplers An array of string used to represent textures
  11018. */
  11019. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11020. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11021. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11022. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11023. if (this._compiledEffects[name]) {
  11024. var compiledEffect = this._compiledEffects[name];
  11025. if (onCompiled && compiledEffect.isReady()) {
  11026. onCompiled(compiledEffect);
  11027. }
  11028. return compiledEffect;
  11029. }
  11030. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11031. effect._key = name;
  11032. this._compiledEffects[name] = effect;
  11033. return effect;
  11034. };
  11035. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11036. if (uniformsNames === void 0) { uniformsNames = []; }
  11037. if (samplers === void 0) { samplers = []; }
  11038. if (defines === void 0) { defines = ""; }
  11039. return this.createEffect({
  11040. vertex: "particles",
  11041. fragmentElement: fragmentName
  11042. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11043. };
  11044. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11045. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11046. context = context || this._gl;
  11047. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11048. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11049. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11050. };
  11051. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11052. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11053. context = context || this._gl;
  11054. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11055. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11056. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11057. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11058. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11059. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11060. return program;
  11061. };
  11062. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11063. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11064. var shaderProgram = context.createProgram();
  11065. if (!shaderProgram) {
  11066. throw new Error("Unable to create program");
  11067. }
  11068. context.attachShader(shaderProgram, vertexShader);
  11069. context.attachShader(shaderProgram, fragmentShader);
  11070. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11071. var transformFeedback = this.createTransformFeedback();
  11072. this.bindTransformFeedback(transformFeedback);
  11073. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11074. shaderProgram.transformFeedback = transformFeedback;
  11075. }
  11076. context.linkProgram(shaderProgram);
  11077. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11078. this.bindTransformFeedback(null);
  11079. }
  11080. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11081. if (!linked) {
  11082. context.validateProgram(shaderProgram);
  11083. var error = context.getProgramInfoLog(shaderProgram);
  11084. if (error) {
  11085. throw new Error(error);
  11086. }
  11087. }
  11088. context.deleteShader(vertexShader);
  11089. context.deleteShader(fragmentShader);
  11090. return shaderProgram;
  11091. };
  11092. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11093. var results = new Array();
  11094. for (var index = 0; index < uniformsNames.length; index++) {
  11095. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11096. }
  11097. return results;
  11098. };
  11099. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11100. var results = [];
  11101. for (var index = 0; index < attributesNames.length; index++) {
  11102. try {
  11103. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11104. }
  11105. catch (e) {
  11106. results.push(-1);
  11107. }
  11108. }
  11109. return results;
  11110. };
  11111. Engine.prototype.enableEffect = function (effect) {
  11112. if (!effect) {
  11113. return;
  11114. }
  11115. // Use program
  11116. this.bindSamplers(effect);
  11117. this._currentEffect = effect;
  11118. if (effect.onBind) {
  11119. effect.onBind(effect);
  11120. }
  11121. effect.onBindObservable.notifyObservers(effect);
  11122. };
  11123. Engine.prototype.setIntArray = function (uniform, array) {
  11124. if (!uniform)
  11125. return;
  11126. this._gl.uniform1iv(uniform, array);
  11127. };
  11128. Engine.prototype.setIntArray2 = function (uniform, array) {
  11129. if (!uniform || array.length % 2 !== 0)
  11130. return;
  11131. this._gl.uniform2iv(uniform, array);
  11132. };
  11133. Engine.prototype.setIntArray3 = function (uniform, array) {
  11134. if (!uniform || array.length % 3 !== 0)
  11135. return;
  11136. this._gl.uniform3iv(uniform, array);
  11137. };
  11138. Engine.prototype.setIntArray4 = function (uniform, array) {
  11139. if (!uniform || array.length % 4 !== 0)
  11140. return;
  11141. this._gl.uniform4iv(uniform, array);
  11142. };
  11143. Engine.prototype.setFloatArray = function (uniform, array) {
  11144. if (!uniform)
  11145. return;
  11146. this._gl.uniform1fv(uniform, array);
  11147. };
  11148. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11149. if (!uniform || array.length % 2 !== 0)
  11150. return;
  11151. this._gl.uniform2fv(uniform, array);
  11152. };
  11153. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11154. if (!uniform || array.length % 3 !== 0)
  11155. return;
  11156. this._gl.uniform3fv(uniform, array);
  11157. };
  11158. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11159. if (!uniform || array.length % 4 !== 0)
  11160. return;
  11161. this._gl.uniform4fv(uniform, array);
  11162. };
  11163. Engine.prototype.setArray = function (uniform, array) {
  11164. if (!uniform)
  11165. return;
  11166. this._gl.uniform1fv(uniform, array);
  11167. };
  11168. Engine.prototype.setArray2 = function (uniform, array) {
  11169. if (!uniform || array.length % 2 !== 0)
  11170. return;
  11171. this._gl.uniform2fv(uniform, array);
  11172. };
  11173. Engine.prototype.setArray3 = function (uniform, array) {
  11174. if (!uniform || array.length % 3 !== 0)
  11175. return;
  11176. this._gl.uniform3fv(uniform, array);
  11177. };
  11178. Engine.prototype.setArray4 = function (uniform, array) {
  11179. if (!uniform || array.length % 4 !== 0)
  11180. return;
  11181. this._gl.uniform4fv(uniform, array);
  11182. };
  11183. Engine.prototype.setMatrices = function (uniform, matrices) {
  11184. if (!uniform)
  11185. return;
  11186. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11187. };
  11188. Engine.prototype.setMatrix = function (uniform, matrix) {
  11189. if (!uniform)
  11190. return;
  11191. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11192. };
  11193. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11194. if (!uniform)
  11195. return;
  11196. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11197. };
  11198. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11199. if (!uniform)
  11200. return;
  11201. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11202. };
  11203. Engine.prototype.setInt = function (uniform, value) {
  11204. if (!uniform)
  11205. return;
  11206. this._gl.uniform1i(uniform, value);
  11207. };
  11208. Engine.prototype.setFloat = function (uniform, value) {
  11209. if (!uniform)
  11210. return;
  11211. this._gl.uniform1f(uniform, value);
  11212. };
  11213. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11214. if (!uniform)
  11215. return;
  11216. this._gl.uniform2f(uniform, x, y);
  11217. };
  11218. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11219. if (!uniform)
  11220. return;
  11221. this._gl.uniform3f(uniform, x, y, z);
  11222. };
  11223. Engine.prototype.setBool = function (uniform, bool) {
  11224. if (!uniform)
  11225. return;
  11226. this._gl.uniform1i(uniform, bool);
  11227. };
  11228. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11229. if (!uniform)
  11230. return;
  11231. this._gl.uniform4f(uniform, x, y, z, w);
  11232. };
  11233. Engine.prototype.setColor3 = function (uniform, color3) {
  11234. if (!uniform)
  11235. return;
  11236. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11237. };
  11238. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11239. if (!uniform)
  11240. return;
  11241. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11242. };
  11243. // States
  11244. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11245. if (zOffset === void 0) { zOffset = 0; }
  11246. if (reverseSide === void 0) { reverseSide = false; }
  11247. // Culling
  11248. if (this._depthCullingState.cull !== culling || force) {
  11249. this._depthCullingState.cull = culling;
  11250. }
  11251. // Cull face
  11252. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11253. if (this._depthCullingState.cullFace !== cullFace || force) {
  11254. this._depthCullingState.cullFace = cullFace;
  11255. }
  11256. // Z offset
  11257. this.setZOffset(zOffset);
  11258. // Front face
  11259. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11260. if (this._depthCullingState.frontFace !== frontFace || force) {
  11261. this._depthCullingState.frontFace = frontFace;
  11262. }
  11263. };
  11264. Engine.prototype.setZOffset = function (value) {
  11265. this._depthCullingState.zOffset = value;
  11266. };
  11267. Engine.prototype.getZOffset = function () {
  11268. return this._depthCullingState.zOffset;
  11269. };
  11270. Engine.prototype.setDepthBuffer = function (enable) {
  11271. this._depthCullingState.depthTest = enable;
  11272. };
  11273. Engine.prototype.getDepthWrite = function () {
  11274. return this._depthCullingState.depthMask;
  11275. };
  11276. Engine.prototype.setDepthWrite = function (enable) {
  11277. this._depthCullingState.depthMask = enable;
  11278. };
  11279. Engine.prototype.setColorWrite = function (enable) {
  11280. this._gl.colorMask(enable, enable, enable, enable);
  11281. this._colorWrite = enable;
  11282. };
  11283. Engine.prototype.getColorWrite = function () {
  11284. return this._colorWrite;
  11285. };
  11286. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11287. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11288. };
  11289. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11290. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11291. if (this._alphaMode === mode) {
  11292. return;
  11293. }
  11294. switch (mode) {
  11295. case Engine.ALPHA_DISABLE:
  11296. this._alphaState.alphaBlend = false;
  11297. break;
  11298. case Engine.ALPHA_PREMULTIPLIED:
  11299. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11300. this._alphaState.alphaBlend = true;
  11301. break;
  11302. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11303. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11304. this._alphaState.alphaBlend = true;
  11305. break;
  11306. case Engine.ALPHA_COMBINE:
  11307. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11308. this._alphaState.alphaBlend = true;
  11309. break;
  11310. case Engine.ALPHA_ONEONE:
  11311. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11312. this._alphaState.alphaBlend = true;
  11313. break;
  11314. case Engine.ALPHA_ADD:
  11315. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11316. this._alphaState.alphaBlend = true;
  11317. break;
  11318. case Engine.ALPHA_SUBTRACT:
  11319. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11320. this._alphaState.alphaBlend = true;
  11321. break;
  11322. case Engine.ALPHA_MULTIPLY:
  11323. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11324. this._alphaState.alphaBlend = true;
  11325. break;
  11326. case Engine.ALPHA_MAXIMIZED:
  11327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11328. this._alphaState.alphaBlend = true;
  11329. break;
  11330. case Engine.ALPHA_INTERPOLATE:
  11331. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11332. this._alphaState.alphaBlend = true;
  11333. break;
  11334. case Engine.ALPHA_SCREENMODE:
  11335. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11336. this._alphaState.alphaBlend = true;
  11337. break;
  11338. }
  11339. if (!noDepthWriteChange) {
  11340. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11341. }
  11342. this._alphaMode = mode;
  11343. };
  11344. Engine.prototype.getAlphaMode = function () {
  11345. return this._alphaMode;
  11346. };
  11347. // Textures
  11348. Engine.prototype.wipeCaches = function (bruteForce) {
  11349. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11350. return;
  11351. }
  11352. this._currentEffect = null;
  11353. // 6/8/2017: deltakosh: Should not be required anymore.
  11354. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11355. if (bruteForce) {
  11356. this.resetTextureCache();
  11357. this._currentProgram = null;
  11358. this._stencilState.reset();
  11359. this._depthCullingState.reset();
  11360. this.setDepthFunctionToLessOrEqual();
  11361. this._alphaState.reset();
  11362. }
  11363. this._resetVertexBufferBinding();
  11364. this._cachedIndexBuffer = null;
  11365. this._cachedEffectForVertexBuffers = null;
  11366. this._unbindVertexArrayObject();
  11367. this.bindIndexBuffer(null);
  11368. };
  11369. /**
  11370. * Set the compressed texture format to use, based on the formats you have, and the formats
  11371. * supported by the hardware / browser.
  11372. *
  11373. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11374. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11375. * to API arguments needed to compressed textures. This puts the burden on the container
  11376. * generator to house the arcane code for determining these for current & future formats.
  11377. *
  11378. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11379. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11380. *
  11381. * Note: The result of this call is not taken into account when a texture is base64.
  11382. *
  11383. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11384. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11385. *
  11386. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11387. * @returns The extension selected.
  11388. */
  11389. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11390. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11391. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11392. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11393. return this._textureFormatInUse = this._texturesSupported[i];
  11394. }
  11395. }
  11396. }
  11397. // actively set format to nothing, to allow this to be called more than once
  11398. // and possibly fail the 2nd time
  11399. this._textureFormatInUse = null;
  11400. return null;
  11401. };
  11402. Engine.prototype._createTexture = function () {
  11403. var texture = this._gl.createTexture();
  11404. if (!texture) {
  11405. throw new Error("Unable to create texture");
  11406. }
  11407. return texture;
  11408. };
  11409. /**
  11410. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11411. * @param {string} urlArg- This contains one of the following:
  11412. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11413. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11414. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11415. *
  11416. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11417. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11418. * @param {Scene} scene- Needed for loading to the correct scene.
  11419. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11420. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11421. * @param {callback} onError- Optional callback to be called upon failure.
  11422. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11423. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11424. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11425. *
  11426. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11427. */
  11428. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11429. var _this = this;
  11430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11431. if (onLoad === void 0) { onLoad = null; }
  11432. if (onError === void 0) { onError = null; }
  11433. if (buffer === void 0) { buffer = null; }
  11434. if (fallBack === void 0) { fallBack = null; }
  11435. if (format === void 0) { format = null; }
  11436. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11437. var fromData = url.substr(0, 5) === "data:";
  11438. var fromBlob = url.substr(0, 5) === "blob:";
  11439. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11440. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11441. // establish the file extension, if possible
  11442. var lastDot = url.lastIndexOf('.');
  11443. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11444. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11445. var isTGA = (extension === ".tga");
  11446. // determine if a ktx file should be substituted
  11447. var isKTX = false;
  11448. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11449. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11450. isKTX = true;
  11451. }
  11452. if (scene) {
  11453. scene._addPendingData(texture);
  11454. }
  11455. texture.url = url;
  11456. texture.generateMipMaps = !noMipmap;
  11457. texture.samplingMode = samplingMode;
  11458. texture.invertY = invertY;
  11459. if (!this._doNotHandleContextLost) {
  11460. // Keep a link to the buffer only if we plan to handle context lost
  11461. texture._buffer = buffer;
  11462. }
  11463. var onLoadObserver = null;
  11464. if (onLoad && !fallBack) {
  11465. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11466. }
  11467. if (!fallBack)
  11468. this._internalTexturesCache.push(texture);
  11469. var onerror = function (message, exception) {
  11470. if (scene) {
  11471. scene._removePendingData(texture);
  11472. }
  11473. if (onLoadObserver) {
  11474. texture.onLoadedObservable.remove(onLoadObserver);
  11475. }
  11476. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11477. if (isKTX) {
  11478. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11479. }
  11480. else if (BABYLON.Tools.UseFallbackTexture) {
  11481. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11482. }
  11483. if (onError) {
  11484. onError(message || "Unknown error", exception);
  11485. }
  11486. };
  11487. var callback = null;
  11488. // processing for non-image formats
  11489. if (isKTX || isTGA || isDDS) {
  11490. if (isKTX) {
  11491. callback = function (data) {
  11492. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11493. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11494. ktx.uploadLevels(_this._gl, !noMipmap);
  11495. return false;
  11496. }, samplingMode);
  11497. };
  11498. }
  11499. else if (isTGA) {
  11500. callback = function (arrayBuffer) {
  11501. var data = new Uint8Array(arrayBuffer);
  11502. var header = BABYLON.TGATools.GetTGAHeader(data);
  11503. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11504. BABYLON.TGATools.UploadContent(_this._gl, data);
  11505. return false;
  11506. }, samplingMode);
  11507. };
  11508. }
  11509. else if (isDDS) {
  11510. callback = function (data) {
  11511. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11512. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11513. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11514. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11515. return false;
  11516. }, samplingMode);
  11517. };
  11518. }
  11519. if (!buffer) {
  11520. this._loadFile(url, function (data) {
  11521. if (callback) {
  11522. callback(data);
  11523. }
  11524. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11525. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11526. });
  11527. }
  11528. else {
  11529. if (callback) {
  11530. callback(buffer);
  11531. }
  11532. }
  11533. // image format processing
  11534. }
  11535. else {
  11536. var onload = function (img) {
  11537. if (fromBlob && !_this._doNotHandleContextLost) {
  11538. // We need to store the image if we need to rebuild the texture
  11539. // in case of a webgl context lost
  11540. texture._buffer = img;
  11541. }
  11542. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11543. var gl = _this._gl;
  11544. var isPot = (img.width === potWidth && img.height === potHeight);
  11545. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11546. if (isPot) {
  11547. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11548. return false;
  11549. }
  11550. // Using shaders to rescale because canvas.drawImage is lossy
  11551. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11552. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11553. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11554. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11555. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11556. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11557. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11558. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11559. _this._releaseTexture(source);
  11560. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11561. continuationCallback();
  11562. });
  11563. return true;
  11564. }, samplingMode);
  11565. };
  11566. if (!fromData || isBase64)
  11567. if (buffer instanceof HTMLImageElement) {
  11568. onload(buffer);
  11569. }
  11570. else {
  11571. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11572. }
  11573. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11574. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11575. else
  11576. onload(buffer);
  11577. }
  11578. return texture;
  11579. };
  11580. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11581. var _this = this;
  11582. var rtt = this.createRenderTargetTexture({
  11583. width: destination.width,
  11584. height: destination.height,
  11585. }, {
  11586. generateMipMaps: false,
  11587. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11588. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11589. generateDepthBuffer: false,
  11590. generateStencilBuffer: false
  11591. });
  11592. if (!this._rescalePostProcess) {
  11593. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11594. }
  11595. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11596. _this._rescalePostProcess.onApply = function (effect) {
  11597. effect._bindTexture("textureSampler", source);
  11598. };
  11599. var hostingScene = scene;
  11600. if (!hostingScene) {
  11601. hostingScene = _this.scenes[_this.scenes.length - 1];
  11602. }
  11603. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11604. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11605. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11606. _this.unBindFramebuffer(rtt);
  11607. _this._releaseTexture(rtt);
  11608. if (onComplete) {
  11609. onComplete();
  11610. }
  11611. });
  11612. };
  11613. Engine.prototype._getInternalFormat = function (format) {
  11614. var internalFormat = this._gl.RGBA;
  11615. switch (format) {
  11616. case Engine.TEXTUREFORMAT_ALPHA:
  11617. internalFormat = this._gl.ALPHA;
  11618. break;
  11619. case Engine.TEXTUREFORMAT_LUMINANCE:
  11620. internalFormat = this._gl.LUMINANCE;
  11621. break;
  11622. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11623. internalFormat = this._gl.LUMINANCE_ALPHA;
  11624. break;
  11625. case Engine.TEXTUREFORMAT_RGB:
  11626. internalFormat = this._gl.RGB;
  11627. break;
  11628. case Engine.TEXTUREFORMAT_RGBA:
  11629. internalFormat = this._gl.RGBA;
  11630. break;
  11631. }
  11632. return internalFormat;
  11633. };
  11634. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11635. if (compression === void 0) { compression = null; }
  11636. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11637. if (!texture) {
  11638. return;
  11639. }
  11640. var internalFormat = this._getInternalFormat(format);
  11641. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11642. var textureType = this._getWebGLTextureType(type);
  11643. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11644. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11645. if (!this._doNotHandleContextLost) {
  11646. texture._bufferView = data;
  11647. texture.format = format;
  11648. texture.type = type;
  11649. texture.invertY = invertY;
  11650. texture._compression = compression;
  11651. }
  11652. if (texture.width % 4 !== 0) {
  11653. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11654. }
  11655. if (compression && data) {
  11656. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11657. }
  11658. else {
  11659. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11660. }
  11661. if (texture.generateMipMaps) {
  11662. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11663. }
  11664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11665. // this.resetTextureCache();
  11666. texture.isReady = true;
  11667. };
  11668. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11669. if (compression === void 0) { compression = null; }
  11670. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11671. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11672. texture.baseWidth = width;
  11673. texture.baseHeight = height;
  11674. texture.width = width;
  11675. texture.height = height;
  11676. texture.format = format;
  11677. texture.generateMipMaps = generateMipMaps;
  11678. texture.samplingMode = samplingMode;
  11679. texture.invertY = invertY;
  11680. texture._compression = compression;
  11681. texture.type = type;
  11682. if (!this._doNotHandleContextLost) {
  11683. texture._bufferView = data;
  11684. }
  11685. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11686. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11687. // Filters
  11688. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11689. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11690. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11691. if (generateMipMaps) {
  11692. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11693. }
  11694. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11695. this._internalTexturesCache.push(texture);
  11696. return texture;
  11697. };
  11698. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11699. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11700. texture.baseWidth = width;
  11701. texture.baseHeight = height;
  11702. if (generateMipMaps) {
  11703. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11704. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11705. }
  11706. // this.resetTextureCache();
  11707. texture.width = width;
  11708. texture.height = height;
  11709. texture.isReady = false;
  11710. texture.generateMipMaps = generateMipMaps;
  11711. texture.samplingMode = samplingMode;
  11712. this.updateTextureSamplingMode(samplingMode, texture);
  11713. this._internalTexturesCache.push(texture);
  11714. return texture;
  11715. };
  11716. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11717. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11718. if (texture.isCube) {
  11719. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11720. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11721. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11722. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11723. }
  11724. else if (texture.is3D) {
  11725. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11726. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11727. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11728. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11729. }
  11730. else {
  11731. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11732. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11733. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11734. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11735. }
  11736. texture.samplingMode = samplingMode;
  11737. };
  11738. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11739. if (premulAlpha === void 0) { premulAlpha = false; }
  11740. if (!texture) {
  11741. return;
  11742. }
  11743. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11744. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11745. if (premulAlpha) {
  11746. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11747. }
  11748. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11749. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11750. if (texture.generateMipMaps) {
  11751. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11752. }
  11753. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11754. if (premulAlpha) {
  11755. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11756. }
  11757. texture.isReady = true;
  11758. };
  11759. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11760. if (!texture || texture._isDisabled) {
  11761. return;
  11762. }
  11763. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11764. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11765. try {
  11766. // Testing video texture support
  11767. if (this._videoTextureSupported === undefined) {
  11768. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11769. if (this._gl.getError() !== 0) {
  11770. this._videoTextureSupported = false;
  11771. }
  11772. else {
  11773. this._videoTextureSupported = true;
  11774. }
  11775. }
  11776. // Copy video through the current working canvas if video texture is not supported
  11777. if (!this._videoTextureSupported) {
  11778. if (!texture._workingCanvas) {
  11779. texture._workingCanvas = document.createElement("canvas");
  11780. var context = texture._workingCanvas.getContext("2d");
  11781. if (!context) {
  11782. throw new Error("Unable to get 2d context");
  11783. }
  11784. texture._workingContext = context;
  11785. texture._workingCanvas.width = texture.width;
  11786. texture._workingCanvas.height = texture.height;
  11787. }
  11788. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11789. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11790. }
  11791. else {
  11792. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11793. }
  11794. if (texture.generateMipMaps) {
  11795. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11796. }
  11797. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11798. // this.resetTextureCache();
  11799. texture.isReady = true;
  11800. }
  11801. catch (ex) {
  11802. // Something unexpected
  11803. // Let's disable the texture
  11804. texture._isDisabled = true;
  11805. }
  11806. };
  11807. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11808. var fullOptions = new RenderTargetCreationOptions();
  11809. if (options !== undefined && typeof options === "object") {
  11810. fullOptions.generateMipMaps = options.generateMipMaps;
  11811. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11812. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11813. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11814. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11815. }
  11816. else {
  11817. fullOptions.generateMipMaps = options;
  11818. fullOptions.generateDepthBuffer = true;
  11819. fullOptions.generateStencilBuffer = false;
  11820. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11821. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11822. }
  11823. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11824. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11825. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11826. }
  11827. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11828. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11829. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11830. }
  11831. var gl = this._gl;
  11832. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11833. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11834. var width = size.width || size;
  11835. var height = size.height || size;
  11836. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11837. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11838. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11839. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11840. }
  11841. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11842. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11843. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11844. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11845. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11846. // Create the framebuffer
  11847. var framebuffer = gl.createFramebuffer();
  11848. this.bindUnboundFramebuffer(framebuffer);
  11849. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11850. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11851. if (fullOptions.generateMipMaps) {
  11852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11853. }
  11854. // Unbind
  11855. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11856. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11857. this.bindUnboundFramebuffer(null);
  11858. texture._framebuffer = framebuffer;
  11859. texture.baseWidth = width;
  11860. texture.baseHeight = height;
  11861. texture.width = width;
  11862. texture.height = height;
  11863. texture.isReady = true;
  11864. texture.samples = 1;
  11865. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11866. texture.samplingMode = fullOptions.samplingMode;
  11867. texture.type = fullOptions.type;
  11868. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11869. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11870. // this.resetTextureCache();
  11871. this._internalTexturesCache.push(texture);
  11872. return texture;
  11873. };
  11874. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11875. var generateMipMaps = false;
  11876. var generateDepthBuffer = true;
  11877. var generateStencilBuffer = false;
  11878. var generateDepthTexture = false;
  11879. var textureCount = 1;
  11880. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11881. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11882. var types = [], samplingModes = [];
  11883. if (options !== undefined) {
  11884. generateMipMaps = options.generateMipMaps;
  11885. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11886. generateStencilBuffer = options.generateStencilBuffer;
  11887. generateDepthTexture = options.generateDepthTexture;
  11888. textureCount = options.textureCount || 1;
  11889. if (options.types) {
  11890. types = options.types;
  11891. }
  11892. if (options.samplingModes) {
  11893. samplingModes = options.samplingModes;
  11894. }
  11895. }
  11896. var gl = this._gl;
  11897. // Create the framebuffer
  11898. var framebuffer = gl.createFramebuffer();
  11899. this.bindUnboundFramebuffer(framebuffer);
  11900. var width = size.width || size;
  11901. var height = size.height || size;
  11902. var textures = [];
  11903. var attachments = [];
  11904. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11905. for (var i = 0; i < textureCount; i++) {
  11906. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11907. var type = types[i] || defaultType;
  11908. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11909. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11910. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11911. }
  11912. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11913. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11914. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11915. }
  11916. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11917. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11918. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11919. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11920. }
  11921. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11922. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11923. textures.push(texture);
  11924. attachments.push(attachment);
  11925. gl.activeTexture(gl["TEXTURE" + i]);
  11926. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11927. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11928. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11930. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11931. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11932. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11933. if (generateMipMaps) {
  11934. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11935. }
  11936. // Unbind
  11937. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11938. texture._framebuffer = framebuffer;
  11939. texture._depthStencilBuffer = depthStencilBuffer;
  11940. texture.baseWidth = width;
  11941. texture.baseHeight = height;
  11942. texture.width = width;
  11943. texture.height = height;
  11944. texture.isReady = true;
  11945. texture.samples = 1;
  11946. texture.generateMipMaps = generateMipMaps;
  11947. texture.samplingMode = samplingMode;
  11948. texture.type = type;
  11949. texture._generateDepthBuffer = generateDepthBuffer;
  11950. texture._generateStencilBuffer = generateStencilBuffer;
  11951. texture._attachments = attachments;
  11952. this._internalTexturesCache.push(texture);
  11953. }
  11954. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11955. // Depth texture
  11956. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11957. gl.activeTexture(gl.TEXTURE0);
  11958. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11959. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11960. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11962. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11963. 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);
  11964. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11965. depthTexture._framebuffer = framebuffer;
  11966. depthTexture.baseWidth = width;
  11967. depthTexture.baseHeight = height;
  11968. depthTexture.width = width;
  11969. depthTexture.height = height;
  11970. depthTexture.isReady = true;
  11971. depthTexture.samples = 1;
  11972. depthTexture.generateMipMaps = generateMipMaps;
  11973. depthTexture.samplingMode = gl.NEAREST;
  11974. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11975. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11976. textures.push(depthTexture);
  11977. this._internalTexturesCache.push(depthTexture);
  11978. }
  11979. gl.drawBuffers(attachments);
  11980. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11981. this.bindUnboundFramebuffer(null);
  11982. this.resetTextureCache();
  11983. return textures;
  11984. };
  11985. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11986. if (samples === void 0) { samples = 1; }
  11987. var depthStencilBuffer = null;
  11988. var gl = this._gl;
  11989. // Create the depth/stencil buffer
  11990. if (generateStencilBuffer) {
  11991. depthStencilBuffer = gl.createRenderbuffer();
  11992. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11993. if (samples > 1) {
  11994. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11995. }
  11996. else {
  11997. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11998. }
  11999. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12000. }
  12001. else if (generateDepthBuffer) {
  12002. depthStencilBuffer = gl.createRenderbuffer();
  12003. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12004. if (samples > 1) {
  12005. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12006. }
  12007. else {
  12008. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12009. }
  12010. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12011. }
  12012. return depthStencilBuffer;
  12013. };
  12014. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12015. if (this.webGLVersion < 2 || !texture) {
  12016. return 1;
  12017. }
  12018. if (texture.samples === samples) {
  12019. return samples;
  12020. }
  12021. var gl = this._gl;
  12022. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12023. // Dispose previous render buffers
  12024. if (texture._depthStencilBuffer) {
  12025. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12026. texture._depthStencilBuffer = null;
  12027. }
  12028. if (texture._MSAAFramebuffer) {
  12029. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12030. texture._MSAAFramebuffer = null;
  12031. }
  12032. if (texture._MSAARenderBuffer) {
  12033. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12034. texture._MSAARenderBuffer = null;
  12035. }
  12036. if (samples > 1) {
  12037. var framebuffer = gl.createFramebuffer();
  12038. if (!framebuffer) {
  12039. throw new Error("Unable to create multi sampled framebuffer");
  12040. }
  12041. texture._MSAAFramebuffer = framebuffer;
  12042. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12043. var colorRenderbuffer = gl.createRenderbuffer();
  12044. if (!colorRenderbuffer) {
  12045. throw new Error("Unable to create multi sampled framebuffer");
  12046. }
  12047. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12048. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12049. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12050. texture._MSAARenderBuffer = colorRenderbuffer;
  12051. }
  12052. else {
  12053. this.bindUnboundFramebuffer(texture._framebuffer);
  12054. }
  12055. texture.samples = samples;
  12056. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12057. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12058. this.bindUnboundFramebuffer(null);
  12059. return samples;
  12060. };
  12061. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12062. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12063. return 1;
  12064. }
  12065. if (textures[0].samples === samples) {
  12066. return samples;
  12067. }
  12068. var gl = this._gl;
  12069. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12070. // Dispose previous render buffers
  12071. if (textures[0]._depthStencilBuffer) {
  12072. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12073. textures[0]._depthStencilBuffer = null;
  12074. }
  12075. if (textures[0]._MSAAFramebuffer) {
  12076. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12077. textures[0]._MSAAFramebuffer = null;
  12078. }
  12079. for (var i = 0; i < textures.length; i++) {
  12080. if (textures[i]._MSAARenderBuffer) {
  12081. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12082. textures[i]._MSAARenderBuffer = null;
  12083. }
  12084. }
  12085. if (samples > 1) {
  12086. var framebuffer = gl.createFramebuffer();
  12087. if (!framebuffer) {
  12088. throw new Error("Unable to create multi sampled framebuffer");
  12089. }
  12090. this.bindUnboundFramebuffer(framebuffer);
  12091. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12092. var attachments = [];
  12093. for (var i = 0; i < textures.length; i++) {
  12094. var texture = textures[i];
  12095. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12096. var colorRenderbuffer = gl.createRenderbuffer();
  12097. if (!colorRenderbuffer) {
  12098. throw new Error("Unable to create multi sampled framebuffer");
  12099. }
  12100. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12101. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12102. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12103. texture._MSAAFramebuffer = framebuffer;
  12104. texture._MSAARenderBuffer = colorRenderbuffer;
  12105. texture.samples = samples;
  12106. texture._depthStencilBuffer = depthStencilBuffer;
  12107. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12108. attachments.push(attachment);
  12109. }
  12110. gl.drawBuffers(attachments);
  12111. }
  12112. else {
  12113. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12114. }
  12115. this.bindUnboundFramebuffer(null);
  12116. return samples;
  12117. };
  12118. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12119. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12120. };
  12121. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12122. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12123. };
  12124. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12125. var gl = this._gl;
  12126. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12127. var generateMipMaps = true;
  12128. var generateDepthBuffer = true;
  12129. var generateStencilBuffer = false;
  12130. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12131. if (options !== undefined) {
  12132. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12133. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12134. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12135. if (options.samplingMode !== undefined) {
  12136. samplingMode = options.samplingMode;
  12137. }
  12138. }
  12139. texture.isCube = true;
  12140. texture.generateMipMaps = generateMipMaps;
  12141. texture.samples = 1;
  12142. texture.samplingMode = samplingMode;
  12143. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12144. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12145. for (var face = 0; face < 6; face++) {
  12146. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12147. }
  12148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12150. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12151. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12152. // Create the framebuffer
  12153. var framebuffer = gl.createFramebuffer();
  12154. this.bindUnboundFramebuffer(framebuffer);
  12155. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12156. // Mipmaps
  12157. if (texture.generateMipMaps) {
  12158. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12159. }
  12160. // Unbind
  12161. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12162. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12163. this.bindUnboundFramebuffer(null);
  12164. texture._framebuffer = framebuffer;
  12165. texture.width = size;
  12166. texture.height = size;
  12167. texture.isReady = true;
  12168. //this.resetTextureCache();
  12169. this._internalTexturesCache.push(texture);
  12170. return texture;
  12171. };
  12172. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12173. var _this = this;
  12174. if (onLoad === void 0) { onLoad = null; }
  12175. if (onError === void 0) { onError = null; }
  12176. if (forcedExtension === void 0) { forcedExtension = null; }
  12177. var callback = function (loadData) {
  12178. if (!loadData) {
  12179. if (onLoad) {
  12180. onLoad(null);
  12181. }
  12182. return;
  12183. }
  12184. var texture = loadData.texture;
  12185. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12186. texture._lodGenerationScale = scale;
  12187. texture._lodGenerationOffset = offset;
  12188. if (_this._caps.textureLOD) {
  12189. // Do not add extra process if texture lod is supported.
  12190. if (onLoad) {
  12191. onLoad(texture);
  12192. }
  12193. return;
  12194. }
  12195. var mipSlices = 3;
  12196. var gl = _this._gl;
  12197. var width = loadData.width;
  12198. if (!width) {
  12199. return;
  12200. }
  12201. var textures = [];
  12202. for (var i = 0; i < mipSlices; i++) {
  12203. //compute LOD from even spacing in smoothness (matching shader calculation)
  12204. var smoothness = i / (mipSlices - 1);
  12205. var roughness = 1 - smoothness;
  12206. var minLODIndex = offset; // roughness = 0
  12207. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12208. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12209. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12210. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12211. glTextureFromLod.isCube = true;
  12212. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12215. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12216. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12217. if (loadData.isDDS) {
  12218. var info = loadData.info;
  12219. var data = loadData.data;
  12220. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12221. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12222. }
  12223. else {
  12224. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12225. }
  12226. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12227. // Wrap in a base texture for easy binding.
  12228. var lodTexture = new BABYLON.BaseTexture(scene);
  12229. lodTexture.isCube = true;
  12230. lodTexture._texture = glTextureFromLod;
  12231. glTextureFromLod.isReady = true;
  12232. textures.push(lodTexture);
  12233. }
  12234. texture._lodTextureHigh = textures[2];
  12235. texture._lodTextureMid = textures[1];
  12236. texture._lodTextureLow = textures[0];
  12237. if (onLoad) {
  12238. onLoad(texture);
  12239. }
  12240. };
  12241. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12242. };
  12243. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12244. var _this = this;
  12245. if (onLoad === void 0) { onLoad = null; }
  12246. if (onError === void 0) { onError = null; }
  12247. if (forcedExtension === void 0) { forcedExtension = null; }
  12248. var gl = this._gl;
  12249. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12250. texture.isCube = true;
  12251. texture.url = rootUrl;
  12252. texture.generateMipMaps = !noMipmap;
  12253. if (!this._doNotHandleContextLost) {
  12254. texture._extension = forcedExtension;
  12255. texture._files = files;
  12256. }
  12257. var isKTX = false;
  12258. var isDDS = false;
  12259. var lastDot = rootUrl.lastIndexOf('.');
  12260. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12261. if (this._textureFormatInUse) {
  12262. extension = this._textureFormatInUse;
  12263. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12264. isKTX = true;
  12265. }
  12266. else {
  12267. isDDS = (extension === ".dds");
  12268. }
  12269. var onerror = function (request, exception) {
  12270. if (onError && request) {
  12271. onError(request.status + " " + request.statusText, exception);
  12272. }
  12273. };
  12274. if (isKTX) {
  12275. this._loadFile(rootUrl, function (data) {
  12276. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12277. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12278. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12279. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12280. ktx.uploadLevels(_this._gl, !noMipmap);
  12281. _this.setCubeMapTextureParams(gl, loadMipmap);
  12282. texture.width = ktx.pixelWidth;
  12283. texture.height = ktx.pixelHeight;
  12284. texture.isReady = true;
  12285. }, undefined, undefined, true, onerror);
  12286. }
  12287. else if (isDDS) {
  12288. if (files && files.length === 6) {
  12289. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12290. var info;
  12291. var loadMipmap = false;
  12292. var width = 0;
  12293. for (var index = 0; index < imgs.length; index++) {
  12294. var data = imgs[index];
  12295. info = BABYLON.DDSTools.GetDDSInfo(data);
  12296. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12297. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12298. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12299. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12300. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12301. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12302. }
  12303. texture.width = info.width;
  12304. texture.height = info.height;
  12305. texture.type = info.textureType;
  12306. width = info.width;
  12307. }
  12308. _this.setCubeMapTextureParams(gl, loadMipmap);
  12309. texture.isReady = true;
  12310. if (onLoad) {
  12311. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12312. }
  12313. }, files, onError);
  12314. }
  12315. else {
  12316. this._loadFile(rootUrl, function (data) {
  12317. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12318. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12319. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12320. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12321. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12322. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12323. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12324. }
  12325. _this.setCubeMapTextureParams(gl, loadMipmap);
  12326. texture.width = info.width;
  12327. texture.height = info.height;
  12328. texture.isReady = true;
  12329. texture.type = info.textureType;
  12330. if (onLoad) {
  12331. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12332. }
  12333. }, undefined, undefined, true, onerror);
  12334. }
  12335. }
  12336. else {
  12337. if (!files) {
  12338. throw new Error("Cannot load cubemap because files were not defined");
  12339. }
  12340. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12341. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12342. var height = width;
  12343. _this._prepareWorkingCanvas();
  12344. if (!_this._workingCanvas || !_this._workingContext) {
  12345. return;
  12346. }
  12347. _this._workingCanvas.width = width;
  12348. _this._workingCanvas.height = height;
  12349. var faces = [
  12350. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12351. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12352. ];
  12353. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12354. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12355. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12356. for (var index = 0; index < faces.length; index++) {
  12357. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12358. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12359. }
  12360. if (!noMipmap) {
  12361. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12362. }
  12363. _this.setCubeMapTextureParams(gl, !noMipmap);
  12364. texture.width = width;
  12365. texture.height = height;
  12366. texture.isReady = true;
  12367. if (format) {
  12368. texture.format = format;
  12369. }
  12370. texture.onLoadedObservable.notifyObservers(texture);
  12371. texture.onLoadedObservable.clear();
  12372. if (onLoad) {
  12373. onLoad();
  12374. }
  12375. }, files, onError);
  12376. }
  12377. this._internalTexturesCache.push(texture);
  12378. return texture;
  12379. };
  12380. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12381. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12382. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12383. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12384. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12385. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12386. // this.resetTextureCache();
  12387. };
  12388. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12389. if (compression === void 0) { compression = null; }
  12390. if (level === void 0) { level = 0; }
  12391. texture._bufferViewArray = data;
  12392. texture.format = format;
  12393. texture.type = type;
  12394. texture.invertY = invertY;
  12395. texture._compression = compression;
  12396. var gl = this._gl;
  12397. var textureType = this._getWebGLTextureType(type);
  12398. var internalFormat = this._getInternalFormat(format);
  12399. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12400. var needConversion = false;
  12401. if (internalFormat === gl.RGB) {
  12402. internalFormat = gl.RGBA;
  12403. needConversion = true;
  12404. }
  12405. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12406. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12407. if (texture.width % 4 !== 0) {
  12408. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12409. }
  12410. // Data are known to be in +X +Y +Z -X -Y -Z
  12411. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12412. var faceData = data[faceIndex];
  12413. if (compression) {
  12414. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12415. }
  12416. else {
  12417. if (needConversion) {
  12418. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12419. }
  12420. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12421. }
  12422. }
  12423. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12424. if (isPot && texture.generateMipMaps && level === 0) {
  12425. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12426. }
  12427. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12428. // this.resetTextureCache();
  12429. texture.isReady = true;
  12430. };
  12431. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12432. if (compression === void 0) { compression = null; }
  12433. var gl = this._gl;
  12434. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12435. texture.isCube = true;
  12436. texture.generateMipMaps = generateMipMaps;
  12437. texture.format = format;
  12438. texture.type = type;
  12439. if (!this._doNotHandleContextLost) {
  12440. texture._bufferViewArray = data;
  12441. }
  12442. var textureType = this._getWebGLTextureType(type);
  12443. var internalFormat = this._getInternalFormat(format);
  12444. if (internalFormat === gl.RGB) {
  12445. internalFormat = gl.RGBA;
  12446. }
  12447. var width = size;
  12448. var height = width;
  12449. texture.width = width;
  12450. texture.height = height;
  12451. // Double check on POT to generate Mips.
  12452. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12453. if (!isPot) {
  12454. generateMipMaps = false;
  12455. }
  12456. // Upload data if needed. The texture won't be ready until then.
  12457. if (data) {
  12458. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12459. }
  12460. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12461. // Filters
  12462. if (data && generateMipMaps) {
  12463. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12464. }
  12465. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12468. }
  12469. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12472. }
  12473. else {
  12474. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12475. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12476. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12477. }
  12478. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12480. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12481. return texture;
  12482. };
  12483. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12484. var _this = this;
  12485. if (onLoad === void 0) { onLoad = null; }
  12486. if (onError === void 0) { onError = null; }
  12487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12488. if (invertY === void 0) { invertY = false; }
  12489. var gl = this._gl;
  12490. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12491. scene._addPendingData(texture);
  12492. texture.url = url;
  12493. this._internalTexturesCache.push(texture);
  12494. var onerror = function (request, exception) {
  12495. scene._removePendingData(texture);
  12496. if (onError && request) {
  12497. onError(request.status + " " + request.statusText, exception);
  12498. }
  12499. };
  12500. var internalCallback = function (data) {
  12501. var width = texture.width;
  12502. var faceDataArrays = callback(data);
  12503. if (!faceDataArrays) {
  12504. return;
  12505. }
  12506. if (mipmmapGenerator) {
  12507. var textureType = _this._getWebGLTextureType(type);
  12508. var internalFormat = _this._getInternalFormat(format);
  12509. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12510. var needConversion = false;
  12511. if (internalFormat === gl.RGB) {
  12512. internalFormat = gl.RGBA;
  12513. needConversion = true;
  12514. }
  12515. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12516. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12517. var mipData = mipmmapGenerator(faceDataArrays);
  12518. for (var level = 0; level < mipData.length; level++) {
  12519. var mipSize = width >> level;
  12520. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12521. var mipFaceData = mipData[level][faceIndex];
  12522. if (needConversion) {
  12523. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12524. }
  12525. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12526. }
  12527. }
  12528. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12529. }
  12530. else {
  12531. texture.generateMipMaps = !noMipmap;
  12532. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12533. }
  12534. texture.isReady = true;
  12535. // this.resetTextureCache();
  12536. scene._removePendingData(texture);
  12537. if (onLoad) {
  12538. onLoad();
  12539. }
  12540. };
  12541. this._loadFile(url, function (data) {
  12542. internalCallback(data);
  12543. }, undefined, scene.database, true, onerror);
  12544. return texture;
  12545. };
  12546. ;
  12547. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12548. if (compression === void 0) { compression = null; }
  12549. var internalFormat = this._getInternalFormat(format);
  12550. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12551. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12552. if (!this._doNotHandleContextLost) {
  12553. texture._bufferView = data;
  12554. texture.format = format;
  12555. texture.invertY = invertY;
  12556. texture._compression = compression;
  12557. }
  12558. if (texture.width % 4 !== 0) {
  12559. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12560. }
  12561. if (compression && data) {
  12562. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12563. }
  12564. else {
  12565. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12566. }
  12567. if (texture.generateMipMaps) {
  12568. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12569. }
  12570. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12571. // this.resetTextureCache();
  12572. texture.isReady = true;
  12573. };
  12574. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12575. if (compression === void 0) { compression = null; }
  12576. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12577. texture.baseWidth = width;
  12578. texture.baseHeight = height;
  12579. texture.baseDepth = depth;
  12580. texture.width = width;
  12581. texture.height = height;
  12582. texture.depth = depth;
  12583. texture.format = format;
  12584. texture.generateMipMaps = generateMipMaps;
  12585. texture.samplingMode = samplingMode;
  12586. texture.is3D = true;
  12587. if (!this._doNotHandleContextLost) {
  12588. texture._bufferView = data;
  12589. }
  12590. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12591. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12592. // Filters
  12593. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12594. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12595. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12596. if (generateMipMaps) {
  12597. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12598. }
  12599. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12600. this._internalTexturesCache.push(texture);
  12601. return texture;
  12602. };
  12603. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12604. var gl = this._gl;
  12605. if (!gl) {
  12606. return;
  12607. }
  12608. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12611. if (!noMipmap && !isCompressed) {
  12612. gl.generateMipmap(gl.TEXTURE_2D);
  12613. }
  12614. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12615. // this.resetTextureCache();
  12616. if (scene) {
  12617. scene._removePendingData(texture);
  12618. }
  12619. texture.onLoadedObservable.notifyObservers(texture);
  12620. texture.onLoadedObservable.clear();
  12621. };
  12622. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12623. var _this = this;
  12624. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12625. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12626. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12627. var gl = this._gl;
  12628. if (!gl) {
  12629. return;
  12630. }
  12631. if (!texture._webGLTexture) {
  12632. // this.resetTextureCache();
  12633. if (scene) {
  12634. scene._removePendingData(texture);
  12635. }
  12636. return;
  12637. }
  12638. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12639. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12640. texture.baseWidth = width;
  12641. texture.baseHeight = height;
  12642. texture.width = potWidth;
  12643. texture.height = potHeight;
  12644. texture.isReady = true;
  12645. if (processFunction(potWidth, potHeight, function () {
  12646. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12647. })) {
  12648. // Returning as texture needs extra async steps
  12649. return;
  12650. }
  12651. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12652. };
  12653. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12654. // Create new RGBA data container.
  12655. var rgbaData;
  12656. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12657. rgbaData = new Float32Array(width * height * 4);
  12658. }
  12659. else {
  12660. rgbaData = new Uint32Array(width * height * 4);
  12661. }
  12662. // Convert each pixel.
  12663. for (var x = 0; x < width; x++) {
  12664. for (var y = 0; y < height; y++) {
  12665. var index = (y * width + x) * 3;
  12666. var newIndex = (y * width + x) * 4;
  12667. // Map Old Value to new value.
  12668. rgbaData[newIndex + 0] = rgbData[index + 0];
  12669. rgbaData[newIndex + 1] = rgbData[index + 1];
  12670. rgbaData[newIndex + 2] = rgbData[index + 2];
  12671. // Add fully opaque alpha channel.
  12672. rgbaData[newIndex + 3] = 1;
  12673. }
  12674. }
  12675. return rgbaData;
  12676. };
  12677. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12678. var gl = this._gl;
  12679. if (texture._framebuffer) {
  12680. gl.deleteFramebuffer(texture._framebuffer);
  12681. texture._framebuffer = null;
  12682. }
  12683. if (texture._depthStencilBuffer) {
  12684. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12685. texture._depthStencilBuffer = null;
  12686. }
  12687. if (texture._MSAAFramebuffer) {
  12688. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12689. texture._MSAAFramebuffer = null;
  12690. }
  12691. if (texture._MSAARenderBuffer) {
  12692. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12693. texture._MSAARenderBuffer = null;
  12694. }
  12695. };
  12696. Engine.prototype._releaseTexture = function (texture) {
  12697. var gl = this._gl;
  12698. this._releaseFramebufferObjects(texture);
  12699. gl.deleteTexture(texture._webGLTexture);
  12700. // Unbind channels
  12701. this.unbindAllTextures();
  12702. var index = this._internalTexturesCache.indexOf(texture);
  12703. if (index !== -1) {
  12704. this._internalTexturesCache.splice(index, 1);
  12705. }
  12706. // Integrated fixed lod samplers.
  12707. if (texture._lodTextureHigh) {
  12708. texture._lodTextureHigh.dispose();
  12709. }
  12710. if (texture._lodTextureMid) {
  12711. texture._lodTextureMid.dispose();
  12712. }
  12713. if (texture._lodTextureLow) {
  12714. texture._lodTextureLow.dispose();
  12715. }
  12716. };
  12717. Engine.prototype.setProgram = function (program) {
  12718. if (this._currentProgram !== program) {
  12719. this._gl.useProgram(program);
  12720. this._currentProgram = program;
  12721. }
  12722. };
  12723. Engine.prototype.bindSamplers = function (effect) {
  12724. this.setProgram(effect.getProgram());
  12725. var samplers = effect.getSamplers();
  12726. for (var index = 0; index < samplers.length; index++) {
  12727. var uniform = effect.getUniform(samplers[index]);
  12728. if (uniform) {
  12729. this._boundUniforms[index] = uniform;
  12730. }
  12731. }
  12732. this._currentEffect = null;
  12733. };
  12734. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12735. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  12736. return;
  12737. }
  12738. // Remove
  12739. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12740. // Bind last to it
  12741. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  12742. // Bind to dummy
  12743. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  12744. };
  12745. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12746. if (!internalTexture) {
  12747. return -1;
  12748. }
  12749. internalTexture._initialSlot = channel;
  12750. if (this.disableTextureBindingOptimization) {
  12751. if (channel !== internalTexture._designatedSlot) {
  12752. this._textureCollisions.addCount(1, false);
  12753. }
  12754. }
  12755. else {
  12756. if (channel !== internalTexture._designatedSlot) {
  12757. if (internalTexture._designatedSlot > -1) {
  12758. return internalTexture._designatedSlot;
  12759. }
  12760. else {
  12761. // No slot for this texture, let's pick a new one (if we find a free slot)
  12762. if (this._nextFreeTextureSlots.length) {
  12763. return this._nextFreeTextureSlots[0];
  12764. }
  12765. // We need to recycle the oldest bound texture, sorry.
  12766. this._textureCollisions.addCount(1, false);
  12767. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  12768. }
  12769. }
  12770. }
  12771. return channel;
  12772. };
  12773. Engine.prototype._linkTrackers = function (previous, next) {
  12774. previous.next = next;
  12775. next.previous = previous;
  12776. };
  12777. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12778. var currentSlot = internalTexture._designatedSlot;
  12779. if (currentSlot === -1) {
  12780. return -1;
  12781. }
  12782. internalTexture._designatedSlot = -1;
  12783. // Remove from bound list
  12784. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12785. // Free the slot
  12786. this._boundTexturesCache[currentSlot] = null;
  12787. this._nextFreeTextureSlots.push(currentSlot);
  12788. return currentSlot;
  12789. };
  12790. Engine.prototype._activateCurrentTexture = function () {
  12791. if (this._currentTextureChannel !== this._activeChannel) {
  12792. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12793. this._currentTextureChannel = this._activeChannel;
  12794. }
  12795. };
  12796. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12797. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12798. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12799. this._activeChannel = texture._designatedSlot;
  12800. }
  12801. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12802. var isTextureForRendering = texture && texture._initialSlot > -1;
  12803. if (currentTextureBound !== texture) {
  12804. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12805. this._removeDesignatedSlot(currentTextureBound);
  12806. }
  12807. this._activateCurrentTexture();
  12808. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12809. this._boundTexturesCache[this._activeChannel] = texture;
  12810. if (texture) {
  12811. if (!this.disableTextureBindingOptimization) {
  12812. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12813. if (slotIndex > -1) {
  12814. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12815. }
  12816. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  12817. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  12818. }
  12819. texture._designatedSlot = this._activeChannel;
  12820. }
  12821. }
  12822. else if (forTextureDataUpdate) {
  12823. this._activateCurrentTexture();
  12824. }
  12825. if (isTextureForRendering && !forTextureDataUpdate) {
  12826. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12827. }
  12828. };
  12829. Engine.prototype._bindTexture = function (channel, texture) {
  12830. if (channel < 0) {
  12831. return;
  12832. }
  12833. if (texture) {
  12834. channel = this._getCorrectTextureChannel(channel, texture);
  12835. }
  12836. this._activeChannel = channel;
  12837. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12838. };
  12839. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12840. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12841. };
  12842. Engine.prototype.unbindAllTextures = function () {
  12843. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12844. this._activeChannel = channel;
  12845. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12846. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12847. if (this.webGLVersion > 1) {
  12848. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12849. }
  12850. }
  12851. };
  12852. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12853. if (channel < 0) {
  12854. return;
  12855. }
  12856. if (uniform) {
  12857. this._boundUniforms[channel] = uniform;
  12858. }
  12859. this._setTexture(channel, texture);
  12860. };
  12861. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12862. var uniform = this._boundUniforms[sourceSlot];
  12863. if (uniform._currentState === destination) {
  12864. return;
  12865. }
  12866. this._gl.uniform1i(uniform, destination);
  12867. uniform._currentState = destination;
  12868. };
  12869. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12870. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12871. // Not ready?
  12872. if (!texture) {
  12873. if (this._boundTexturesCache[channel] != null) {
  12874. this._activeChannel = channel;
  12875. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12876. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12877. if (this.webGLVersion > 1) {
  12878. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12879. }
  12880. }
  12881. return false;
  12882. }
  12883. // Video
  12884. if (texture.video) {
  12885. this._activeChannel = channel;
  12886. texture.update();
  12887. }
  12888. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12889. texture.delayLoad();
  12890. return false;
  12891. }
  12892. var internalTexture;
  12893. if (texture.isReady()) {
  12894. internalTexture = texture.getInternalTexture();
  12895. }
  12896. else if (texture.isCube) {
  12897. internalTexture = this.emptyCubeTexture;
  12898. }
  12899. else if (texture.is3D) {
  12900. internalTexture = this.emptyTexture3D;
  12901. }
  12902. else {
  12903. internalTexture = this.emptyTexture;
  12904. }
  12905. if (!isPartOfTextureArray) {
  12906. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12907. }
  12908. if (this._boundTexturesCache[channel] === internalTexture) {
  12909. this._moveBoundTextureOnTop(internalTexture);
  12910. if (!isPartOfTextureArray) {
  12911. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12912. }
  12913. return false;
  12914. }
  12915. this._activeChannel = channel;
  12916. if (internalTexture && internalTexture.is3D) {
  12917. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12918. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12919. internalTexture._cachedWrapU = texture.wrapU;
  12920. switch (texture.wrapU) {
  12921. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12922. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12923. break;
  12924. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12925. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12926. break;
  12927. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12928. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12929. break;
  12930. }
  12931. }
  12932. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12933. internalTexture._cachedWrapV = texture.wrapV;
  12934. switch (texture.wrapV) {
  12935. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12936. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12937. break;
  12938. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12939. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12940. break;
  12941. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12942. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12943. break;
  12944. }
  12945. }
  12946. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12947. internalTexture._cachedWrapR = texture.wrapR;
  12948. switch (texture.wrapV) {
  12949. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12950. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12951. break;
  12952. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12953. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12954. break;
  12955. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12956. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12957. break;
  12958. }
  12959. }
  12960. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12961. }
  12962. else if (internalTexture && internalTexture.isCube) {
  12963. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12964. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12965. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12966. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12967. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12968. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12969. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12970. }
  12971. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12972. }
  12973. else {
  12974. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12975. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12976. internalTexture._cachedWrapU = texture.wrapU;
  12977. switch (texture.wrapU) {
  12978. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12979. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12980. break;
  12981. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12982. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12983. break;
  12984. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12985. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12986. break;
  12987. }
  12988. }
  12989. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12990. internalTexture._cachedWrapV = texture.wrapV;
  12991. switch (texture.wrapV) {
  12992. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12993. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12994. break;
  12995. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12996. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12997. break;
  12998. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12999. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13000. break;
  13001. }
  13002. }
  13003. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13004. }
  13005. return true;
  13006. };
  13007. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13008. if (channel < 0 || !uniform) {
  13009. return;
  13010. }
  13011. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13012. this._textureUnits = new Int32Array(textures.length);
  13013. }
  13014. for (var i = 0; i < textures.length; i++) {
  13015. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13016. }
  13017. this._gl.uniform1iv(uniform, this._textureUnits);
  13018. for (var index = 0; index < textures.length; index++) {
  13019. this._setTexture(this._textureUnits[index], textures[index], true);
  13020. }
  13021. };
  13022. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13023. var internalTexture = texture.getInternalTexture();
  13024. if (!internalTexture) {
  13025. return;
  13026. }
  13027. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13028. var value = texture.anisotropicFilteringLevel;
  13029. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13030. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13031. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13032. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13033. }
  13034. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13035. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13036. internalTexture._cachedAnisotropicFilteringLevel = value;
  13037. }
  13038. };
  13039. Engine.prototype.readPixels = function (x, y, width, height) {
  13040. var data = new Uint8Array(height * width * 4);
  13041. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13042. return data;
  13043. };
  13044. /**
  13045. * Add an externaly attached data from its key.
  13046. * This method call will fail and return false, if such key already exists.
  13047. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13048. * @param key the unique key that identifies the data
  13049. * @param data the data object to associate to the key for this Engine instance
  13050. * @return true if no such key were already present and the data was added successfully, false otherwise
  13051. */
  13052. Engine.prototype.addExternalData = function (key, data) {
  13053. if (!this._externalData) {
  13054. this._externalData = new BABYLON.StringDictionary();
  13055. }
  13056. return this._externalData.add(key, data);
  13057. };
  13058. /**
  13059. * Get an externaly attached data from its key
  13060. * @param key the unique key that identifies the data
  13061. * @return the associated data, if present (can be null), or undefined if not present
  13062. */
  13063. Engine.prototype.getExternalData = function (key) {
  13064. if (!this._externalData) {
  13065. this._externalData = new BABYLON.StringDictionary();
  13066. }
  13067. return this._externalData.get(key);
  13068. };
  13069. /**
  13070. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13071. * @param key the unique key that identifies the data
  13072. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13073. * @return the associated data, can be null if the factory returned null.
  13074. */
  13075. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13076. if (!this._externalData) {
  13077. this._externalData = new BABYLON.StringDictionary();
  13078. }
  13079. return this._externalData.getOrAddWithFactory(key, factory);
  13080. };
  13081. /**
  13082. * Remove an externaly attached data from the Engine instance
  13083. * @param key the unique key that identifies the data
  13084. * @return true if the data was successfully removed, false if it doesn't exist
  13085. */
  13086. Engine.prototype.removeExternalData = function (key) {
  13087. if (!this._externalData) {
  13088. this._externalData = new BABYLON.StringDictionary();
  13089. }
  13090. return this._externalData.remove(key);
  13091. };
  13092. Engine.prototype.unbindAllAttributes = function () {
  13093. if (this._mustWipeVertexAttributes) {
  13094. this._mustWipeVertexAttributes = false;
  13095. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13096. this._gl.disableVertexAttribArray(i);
  13097. this._vertexAttribArraysEnabled[i] = false;
  13098. this._currentBufferPointers[i].active = false;
  13099. }
  13100. return;
  13101. }
  13102. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13103. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13104. continue;
  13105. }
  13106. this._gl.disableVertexAttribArray(i);
  13107. this._vertexAttribArraysEnabled[i] = false;
  13108. this._currentBufferPointers[i].active = false;
  13109. }
  13110. };
  13111. Engine.prototype.releaseEffects = function () {
  13112. for (var name in this._compiledEffects) {
  13113. this._deleteProgram(this._compiledEffects[name]._program);
  13114. }
  13115. this._compiledEffects = {};
  13116. };
  13117. // Dispose
  13118. Engine.prototype.dispose = function () {
  13119. this.hideLoadingUI();
  13120. this.stopRenderLoop();
  13121. // Release postProcesses
  13122. while (this.postProcesses.length) {
  13123. this.postProcesses[0].dispose();
  13124. }
  13125. // Empty texture
  13126. if (this._emptyTexture) {
  13127. this._releaseTexture(this._emptyTexture);
  13128. this._emptyTexture = null;
  13129. }
  13130. if (this._emptyCubeTexture) {
  13131. this._releaseTexture(this._emptyCubeTexture);
  13132. this._emptyCubeTexture = null;
  13133. }
  13134. // Rescale PP
  13135. if (this._rescalePostProcess) {
  13136. this._rescalePostProcess.dispose();
  13137. }
  13138. // Release scenes
  13139. while (this.scenes.length) {
  13140. this.scenes[0].dispose();
  13141. }
  13142. // Release audio engine
  13143. if (Engine.audioEngine) {
  13144. Engine.audioEngine.dispose();
  13145. }
  13146. // Release effects
  13147. this.releaseEffects();
  13148. // Unbind
  13149. this.unbindAllAttributes();
  13150. if (this._dummyFramebuffer) {
  13151. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13152. }
  13153. //WebVR
  13154. this.disableVR();
  13155. // Events
  13156. if (BABYLON.Tools.IsWindowObjectExist()) {
  13157. window.removeEventListener("blur", this._onBlur);
  13158. window.removeEventListener("focus", this._onFocus);
  13159. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13160. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13161. if (this._renderingCanvas) {
  13162. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13163. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13164. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13165. if (!this._doNotHandleContextLost) {
  13166. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13167. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13168. }
  13169. }
  13170. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13171. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13172. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13173. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13174. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13175. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13176. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13177. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13178. if (this._onVrDisplayConnect) {
  13179. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13180. if (this._onVrDisplayDisconnect) {
  13181. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13182. }
  13183. if (this._onVrDisplayPresentChange) {
  13184. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13185. }
  13186. this._onVrDisplayConnect = null;
  13187. this._onVrDisplayDisconnect = null;
  13188. }
  13189. }
  13190. // Remove from Instances
  13191. var index = Engine.Instances.indexOf(this);
  13192. if (index >= 0) {
  13193. Engine.Instances.splice(index, 1);
  13194. }
  13195. this._workingCanvas = null;
  13196. this._workingContext = null;
  13197. this._currentBufferPointers = [];
  13198. this._renderingCanvas = null;
  13199. this._currentProgram = null;
  13200. this.onResizeObservable.clear();
  13201. this.onCanvasBlurObservable.clear();
  13202. this.onCanvasFocusObservable.clear();
  13203. this.onCanvasPointerOutObservable.clear();
  13204. this.onBeginFrameObservable.clear();
  13205. this.onEndFrameObservable.clear();
  13206. BABYLON.Effect.ResetCache();
  13207. // Abort active requests
  13208. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13209. var request = _a[_i];
  13210. request.abort();
  13211. }
  13212. };
  13213. // Loading screen
  13214. Engine.prototype.displayLoadingUI = function () {
  13215. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13216. return;
  13217. }
  13218. var loadingScreen = this.loadingScreen;
  13219. if (loadingScreen) {
  13220. loadingScreen.displayLoadingUI();
  13221. }
  13222. };
  13223. Engine.prototype.hideLoadingUI = function () {
  13224. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13225. return;
  13226. }
  13227. var loadingScreen = this.loadingScreen;
  13228. if (loadingScreen) {
  13229. loadingScreen.hideLoadingUI();
  13230. }
  13231. };
  13232. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13233. get: function () {
  13234. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13235. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13236. return this._loadingScreen;
  13237. },
  13238. set: function (loadingScreen) {
  13239. this._loadingScreen = loadingScreen;
  13240. },
  13241. enumerable: true,
  13242. configurable: true
  13243. });
  13244. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13245. set: function (text) {
  13246. this.loadingScreen.loadingUIText = text;
  13247. },
  13248. enumerable: true,
  13249. configurable: true
  13250. });
  13251. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13252. set: function (color) {
  13253. this.loadingScreen.loadingUIBackgroundColor = color;
  13254. },
  13255. enumerable: true,
  13256. configurable: true
  13257. });
  13258. Engine.prototype.attachContextLostEvent = function (callback) {
  13259. if (this._renderingCanvas) {
  13260. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13261. }
  13262. };
  13263. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13264. if (this._renderingCanvas) {
  13265. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13266. }
  13267. };
  13268. Engine.prototype.getVertexShaderSource = function (program) {
  13269. var shaders = this._gl.getAttachedShaders(program);
  13270. if (!shaders) {
  13271. return null;
  13272. }
  13273. return this._gl.getShaderSource(shaders[0]);
  13274. };
  13275. Engine.prototype.getFragmentShaderSource = function (program) {
  13276. var shaders = this._gl.getAttachedShaders(program);
  13277. if (!shaders) {
  13278. return null;
  13279. }
  13280. return this._gl.getShaderSource(shaders[1]);
  13281. };
  13282. Engine.prototype.getError = function () {
  13283. return this._gl.getError();
  13284. };
  13285. // FPS
  13286. Engine.prototype.getFps = function () {
  13287. return this._fps;
  13288. };
  13289. Engine.prototype.getDeltaTime = function () {
  13290. return this._deltaTime;
  13291. };
  13292. Engine.prototype._measureFps = function () {
  13293. this._performanceMonitor.sampleFrame();
  13294. this._fps = this._performanceMonitor.averageFPS;
  13295. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13296. };
  13297. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13298. if (faceIndex === void 0) { faceIndex = -1; }
  13299. var gl = this._gl;
  13300. if (!this._dummyFramebuffer) {
  13301. var dummy = gl.createFramebuffer();
  13302. if (!dummy) {
  13303. throw new Error("Unable to create dummy framebuffer");
  13304. }
  13305. this._dummyFramebuffer = dummy;
  13306. }
  13307. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13308. if (faceIndex > -1) {
  13309. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13310. }
  13311. else {
  13312. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13313. }
  13314. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13315. var buffer;
  13316. switch (readType) {
  13317. case gl.UNSIGNED_BYTE:
  13318. buffer = new Uint8Array(4 * width * height);
  13319. readType = gl.UNSIGNED_BYTE;
  13320. break;
  13321. default:
  13322. buffer = new Float32Array(4 * width * height);
  13323. readType = gl.FLOAT;
  13324. break;
  13325. }
  13326. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13327. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13328. return buffer;
  13329. };
  13330. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13331. if (this._webGLVersion > 1) {
  13332. return this._caps.colorBufferFloat;
  13333. }
  13334. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13335. };
  13336. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13337. if (this._webGLVersion > 1) {
  13338. return this._caps.colorBufferFloat;
  13339. }
  13340. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13341. };
  13342. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13343. Engine.prototype._canRenderToFramebuffer = function (type) {
  13344. var gl = this._gl;
  13345. //clear existing errors
  13346. while (gl.getError() !== gl.NO_ERROR) { }
  13347. var successful = true;
  13348. var texture = gl.createTexture();
  13349. gl.bindTexture(gl.TEXTURE_2D, texture);
  13350. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13353. var fb = gl.createFramebuffer();
  13354. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13355. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13356. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13357. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13358. successful = successful && (gl.getError() === gl.NO_ERROR);
  13359. //try render by clearing frame buffer's color buffer
  13360. if (successful) {
  13361. gl.clear(gl.COLOR_BUFFER_BIT);
  13362. successful = successful && (gl.getError() === gl.NO_ERROR);
  13363. }
  13364. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13365. if (successful) {
  13366. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13367. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13368. var readFormat = gl.RGBA;
  13369. var readType = gl.UNSIGNED_BYTE;
  13370. var buffer = new Uint8Array(4);
  13371. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13372. successful = successful && (gl.getError() === gl.NO_ERROR);
  13373. }
  13374. //clean up
  13375. gl.deleteTexture(texture);
  13376. gl.deleteFramebuffer(fb);
  13377. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13378. //clear accumulated errors
  13379. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13380. return successful;
  13381. };
  13382. Engine.prototype._getWebGLTextureType = function (type) {
  13383. if (type === Engine.TEXTURETYPE_FLOAT) {
  13384. return this._gl.FLOAT;
  13385. }
  13386. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13387. // Add Half Float Constant.
  13388. return this._gl.HALF_FLOAT_OES;
  13389. }
  13390. return this._gl.UNSIGNED_BYTE;
  13391. };
  13392. ;
  13393. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13394. if (this._webGLVersion === 1) {
  13395. return this._gl.RGBA;
  13396. }
  13397. if (type === Engine.TEXTURETYPE_FLOAT) {
  13398. return this._gl.RGBA32F;
  13399. }
  13400. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13401. return this._gl.RGBA16F;
  13402. }
  13403. return this._gl.RGBA;
  13404. };
  13405. ;
  13406. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13407. if (type === Engine.TEXTURETYPE_FLOAT) {
  13408. return this._gl.RGBA32F;
  13409. }
  13410. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13411. return this._gl.RGBA16F;
  13412. }
  13413. return this._gl.RGBA8;
  13414. };
  13415. ;
  13416. Engine.prototype.createQuery = function () {
  13417. return this._gl.createQuery();
  13418. };
  13419. Engine.prototype.deleteQuery = function (query) {
  13420. this._gl.deleteQuery(query);
  13421. return this;
  13422. };
  13423. Engine.prototype.isQueryResultAvailable = function (query) {
  13424. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13425. };
  13426. Engine.prototype.getQueryResult = function (query) {
  13427. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13428. };
  13429. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13430. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13431. this._gl.beginQuery(glAlgorithm, query);
  13432. return this;
  13433. };
  13434. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13435. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13436. this._gl.endQuery(glAlgorithm);
  13437. return this;
  13438. };
  13439. /* Time queries */
  13440. Engine.prototype._createTimeQuery = function () {
  13441. var timerQuery = this._caps.timerQuery;
  13442. if (timerQuery.createQueryEXT) {
  13443. return timerQuery.createQueryEXT();
  13444. }
  13445. return this.createQuery();
  13446. };
  13447. Engine.prototype._deleteTimeQuery = function (query) {
  13448. var timerQuery = this._caps.timerQuery;
  13449. if (timerQuery.deleteQueryEXT) {
  13450. timerQuery.deleteQueryEXT(query);
  13451. return;
  13452. }
  13453. this.deleteQuery(query);
  13454. };
  13455. Engine.prototype._getTimeQueryResult = function (query) {
  13456. var timerQuery = this._caps.timerQuery;
  13457. if (timerQuery.getQueryObjectEXT) {
  13458. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13459. }
  13460. return this.getQueryResult(query);
  13461. };
  13462. Engine.prototype._getTimeQueryAvailability = function (query) {
  13463. var timerQuery = this._caps.timerQuery;
  13464. if (timerQuery.getQueryObjectEXT) {
  13465. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13466. }
  13467. return this.isQueryResultAvailable(query);
  13468. };
  13469. Engine.prototype.startTimeQuery = function () {
  13470. var timerQuery = this._caps.timerQuery;
  13471. if (!timerQuery) {
  13472. return null;
  13473. }
  13474. var token = new BABYLON._TimeToken();
  13475. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13476. if (this._caps.canUseTimestampForTimerQuery) {
  13477. token._startTimeQuery = this._createTimeQuery();
  13478. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13479. }
  13480. else {
  13481. if (this._currentNonTimestampToken) {
  13482. return this._currentNonTimestampToken;
  13483. }
  13484. token._timeElapsedQuery = this._createTimeQuery();
  13485. if (timerQuery.beginQueryEXT) {
  13486. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13487. }
  13488. else {
  13489. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13490. }
  13491. this._currentNonTimestampToken = token;
  13492. }
  13493. return token;
  13494. };
  13495. Engine.prototype.endTimeQuery = function (token) {
  13496. var timerQuery = this._caps.timerQuery;
  13497. if (!timerQuery || !token) {
  13498. return -1;
  13499. }
  13500. if (this._caps.canUseTimestampForTimerQuery) {
  13501. if (!token._startTimeQuery) {
  13502. return -1;
  13503. }
  13504. if (!token._endTimeQuery) {
  13505. token._endTimeQuery = this._createTimeQuery();
  13506. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13507. }
  13508. }
  13509. else if (!token._timeElapsedQueryEnded) {
  13510. if (!token._timeElapsedQuery) {
  13511. return -1;
  13512. }
  13513. if (timerQuery.endQueryEXT) {
  13514. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13515. }
  13516. else {
  13517. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13518. }
  13519. token._timeElapsedQueryEnded = true;
  13520. }
  13521. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13522. var available = false;
  13523. if (token._endTimeQuery) {
  13524. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13525. }
  13526. else if (token._timeElapsedQuery) {
  13527. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13528. }
  13529. if (available && !disjoint) {
  13530. var result = 0;
  13531. if (this._caps.canUseTimestampForTimerQuery) {
  13532. if (!token._startTimeQuery || !token._endTimeQuery) {
  13533. return -1;
  13534. }
  13535. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13536. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13537. result = timeEnd - timeStart;
  13538. this._deleteTimeQuery(token._startTimeQuery);
  13539. this._deleteTimeQuery(token._endTimeQuery);
  13540. token._startTimeQuery = null;
  13541. token._endTimeQuery = null;
  13542. }
  13543. else {
  13544. if (!token._timeElapsedQuery) {
  13545. return -1;
  13546. }
  13547. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13548. this._deleteTimeQuery(token._timeElapsedQuery);
  13549. token._timeElapsedQuery = null;
  13550. token._timeElapsedQueryEnded = false;
  13551. this._currentNonTimestampToken = null;
  13552. }
  13553. return result;
  13554. }
  13555. return -1;
  13556. };
  13557. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13558. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13559. };
  13560. // Transform feedback
  13561. Engine.prototype.createTransformFeedback = function () {
  13562. return this._gl.createTransformFeedback();
  13563. };
  13564. Engine.prototype.deleteTransformFeedback = function (value) {
  13565. this._gl.deleteTransformFeedback(value);
  13566. };
  13567. Engine.prototype.bindTransformFeedback = function (value) {
  13568. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13569. };
  13570. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13571. if (usePoints === void 0) { usePoints = true; }
  13572. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13573. };
  13574. Engine.prototype.endTransformFeedback = function () {
  13575. this._gl.endTransformFeedback();
  13576. };
  13577. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13578. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13579. };
  13580. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13581. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13582. };
  13583. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13584. var _this = this;
  13585. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13586. this._activeRequests.push(request);
  13587. request.onCompleteObservable.add(function (request) {
  13588. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13589. });
  13590. return request;
  13591. };
  13592. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13593. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13594. var onload = function (data) {
  13595. loadedFiles[index] = data;
  13596. loadedFiles._internalCount++;
  13597. if (loadedFiles._internalCount === 6) {
  13598. onfinish(loadedFiles);
  13599. }
  13600. };
  13601. var onerror = function (request, exception) {
  13602. if (onErrorCallBack && request) {
  13603. onErrorCallBack(request.status + " " + request.statusText, exception);
  13604. }
  13605. };
  13606. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13607. };
  13608. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13609. if (onError === void 0) { onError = null; }
  13610. var loadedFiles = [];
  13611. loadedFiles._internalCount = 0;
  13612. for (var index = 0; index < 6; index++) {
  13613. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13614. }
  13615. };
  13616. // Statics
  13617. Engine.isSupported = function () {
  13618. try {
  13619. var tempcanvas = document.createElement("canvas");
  13620. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13621. return gl != null && !!window.WebGLRenderingContext;
  13622. }
  13623. catch (e) {
  13624. return false;
  13625. }
  13626. };
  13627. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13628. Engine.ExceptionList = [
  13629. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13630. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13631. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13632. ];
  13633. Engine.Instances = new Array();
  13634. // Const statics
  13635. Engine._ALPHA_DISABLE = 0;
  13636. Engine._ALPHA_ADD = 1;
  13637. Engine._ALPHA_COMBINE = 2;
  13638. Engine._ALPHA_SUBTRACT = 3;
  13639. Engine._ALPHA_MULTIPLY = 4;
  13640. Engine._ALPHA_MAXIMIZED = 5;
  13641. Engine._ALPHA_ONEONE = 6;
  13642. Engine._ALPHA_PREMULTIPLIED = 7;
  13643. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13644. Engine._ALPHA_INTERPOLATE = 9;
  13645. Engine._ALPHA_SCREENMODE = 10;
  13646. Engine._DELAYLOADSTATE_NONE = 0;
  13647. Engine._DELAYLOADSTATE_LOADED = 1;
  13648. Engine._DELAYLOADSTATE_LOADING = 2;
  13649. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13650. Engine._TEXTUREFORMAT_ALPHA = 0;
  13651. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13652. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13653. Engine._TEXTUREFORMAT_RGB = 4;
  13654. Engine._TEXTUREFORMAT_RGBA = 5;
  13655. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13656. Engine._TEXTURETYPE_FLOAT = 1;
  13657. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13658. // Depht or Stencil test Constants.
  13659. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13660. 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.
  13661. 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.
  13662. 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.
  13663. 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.
  13664. 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.
  13665. 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.
  13666. 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.
  13667. // Stencil Actions Constants.
  13668. Engine._KEEP = 0x1E00;
  13669. Engine._REPLACE = 0x1E01;
  13670. Engine._INCR = 0x1E02;
  13671. Engine._DECR = 0x1E03;
  13672. Engine._INVERT = 0x150A;
  13673. Engine._INCR_WRAP = 0x8507;
  13674. Engine._DECR_WRAP = 0x8508;
  13675. // Texture rescaling mode
  13676. Engine._SCALEMODE_FLOOR = 1;
  13677. Engine._SCALEMODE_NEAREST = 2;
  13678. Engine._SCALEMODE_CEILING = 3;
  13679. // Updatable statics so stick with vars here
  13680. Engine.CollisionsEpsilon = 0.001;
  13681. Engine.CodeRepository = "src/";
  13682. Engine.ShadersRepository = "src/Shaders/";
  13683. return Engine;
  13684. }());
  13685. BABYLON.Engine = Engine;
  13686. })(BABYLON || (BABYLON = {}));
  13687. //# sourceMappingURL=babylon.engine.js.map
  13688. var BABYLON;
  13689. (function (BABYLON) {
  13690. /**
  13691. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13692. */
  13693. var Node = /** @class */ (function () {
  13694. /**
  13695. * @constructor
  13696. * @param {string} name - the name and id to be given to this node
  13697. * @param {BABYLON.Scene} the scene this node will be added to
  13698. */
  13699. function Node(name, scene) {
  13700. if (scene === void 0) { scene = null; }
  13701. this.state = "";
  13702. this.metadata = null;
  13703. this.doNotSerialize = false;
  13704. this.animations = new Array();
  13705. this._ranges = {};
  13706. this._isEnabled = true;
  13707. this._isReady = true;
  13708. this._currentRenderId = -1;
  13709. this._parentRenderId = -1;
  13710. /**
  13711. * An event triggered when the mesh is disposed.
  13712. * @type {BABYLON.Observable}
  13713. */
  13714. this.onDisposeObservable = new BABYLON.Observable();
  13715. // Behaviors
  13716. this._behaviors = new Array();
  13717. this.name = name;
  13718. this.id = name;
  13719. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13720. this.uniqueId = this._scene.getUniqueId();
  13721. this._initCache();
  13722. }
  13723. Object.defineProperty(Node.prototype, "parent", {
  13724. get: function () {
  13725. return this._parentNode;
  13726. },
  13727. set: function (parent) {
  13728. if (this._parentNode === parent) {
  13729. return;
  13730. }
  13731. // Remove self from list of children of parent
  13732. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13733. var index = this._parentNode._children.indexOf(this);
  13734. if (index !== -1) {
  13735. this._parentNode._children.splice(index, 1);
  13736. }
  13737. }
  13738. // Store new parent
  13739. this._parentNode = parent;
  13740. // Add as child to new parent
  13741. if (this._parentNode) {
  13742. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13743. this._parentNode._children = new Array();
  13744. }
  13745. this._parentNode._children.push(this);
  13746. }
  13747. },
  13748. enumerable: true,
  13749. configurable: true
  13750. });
  13751. Node.prototype.getClassName = function () {
  13752. return "Node";
  13753. };
  13754. Object.defineProperty(Node.prototype, "onDispose", {
  13755. set: function (callback) {
  13756. if (this._onDisposeObserver) {
  13757. this.onDisposeObservable.remove(this._onDisposeObserver);
  13758. }
  13759. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13760. },
  13761. enumerable: true,
  13762. configurable: true
  13763. });
  13764. Node.prototype.getScene = function () {
  13765. return this._scene;
  13766. };
  13767. Node.prototype.getEngine = function () {
  13768. return this._scene.getEngine();
  13769. };
  13770. Node.prototype.addBehavior = function (behavior) {
  13771. var _this = this;
  13772. var index = this._behaviors.indexOf(behavior);
  13773. if (index !== -1) {
  13774. return this;
  13775. }
  13776. behavior.init();
  13777. if (this._scene.isLoading) {
  13778. // We defer the attach when the scene will be loaded
  13779. var observer = this._scene.onDataLoadedObservable.add(function () {
  13780. behavior.attach(_this);
  13781. setTimeout(function () {
  13782. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13783. _this._scene.onDataLoadedObservable.remove(observer);
  13784. }, 0);
  13785. });
  13786. }
  13787. else {
  13788. behavior.attach(this);
  13789. }
  13790. this._behaviors.push(behavior);
  13791. return this;
  13792. };
  13793. Node.prototype.removeBehavior = function (behavior) {
  13794. var index = this._behaviors.indexOf(behavior);
  13795. if (index === -1) {
  13796. return this;
  13797. }
  13798. this._behaviors[index].detach();
  13799. this._behaviors.splice(index, 1);
  13800. return this;
  13801. };
  13802. Object.defineProperty(Node.prototype, "behaviors", {
  13803. get: function () {
  13804. return this._behaviors;
  13805. },
  13806. enumerable: true,
  13807. configurable: true
  13808. });
  13809. Node.prototype.getBehaviorByName = function (name) {
  13810. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13811. var behavior = _a[_i];
  13812. if (behavior.name === name) {
  13813. return behavior;
  13814. }
  13815. }
  13816. return null;
  13817. };
  13818. // override it in derived class
  13819. Node.prototype.getWorldMatrix = function () {
  13820. return BABYLON.Matrix.Identity();
  13821. };
  13822. // override it in derived class if you add new variables to the cache
  13823. // and call the parent class method
  13824. Node.prototype._initCache = function () {
  13825. this._cache = {};
  13826. this._cache.parent = undefined;
  13827. };
  13828. Node.prototype.updateCache = function (force) {
  13829. if (!force && this.isSynchronized())
  13830. return;
  13831. this._cache.parent = this.parent;
  13832. this._updateCache();
  13833. };
  13834. // override it in derived class if you add new variables to the cache
  13835. // and call the parent class method if !ignoreParentClass
  13836. Node.prototype._updateCache = function (ignoreParentClass) {
  13837. };
  13838. // override it in derived class if you add new variables to the cache
  13839. Node.prototype._isSynchronized = function () {
  13840. return true;
  13841. };
  13842. Node.prototype._markSyncedWithParent = function () {
  13843. if (this.parent) {
  13844. this._parentRenderId = this.parent._currentRenderId;
  13845. }
  13846. };
  13847. Node.prototype.isSynchronizedWithParent = function () {
  13848. if (!this.parent) {
  13849. return true;
  13850. }
  13851. if (this._parentRenderId !== this.parent._currentRenderId) {
  13852. return false;
  13853. }
  13854. return this.parent.isSynchronized();
  13855. };
  13856. Node.prototype.isSynchronized = function (updateCache) {
  13857. var check = this.hasNewParent();
  13858. check = check || !this.isSynchronizedWithParent();
  13859. check = check || !this._isSynchronized();
  13860. if (updateCache)
  13861. this.updateCache(true);
  13862. return !check;
  13863. };
  13864. Node.prototype.hasNewParent = function (update) {
  13865. if (this._cache.parent === this.parent)
  13866. return false;
  13867. if (update)
  13868. this._cache.parent = this.parent;
  13869. return true;
  13870. };
  13871. /**
  13872. * Is this node ready to be used/rendered
  13873. * @return {boolean} is it ready
  13874. */
  13875. Node.prototype.isReady = function () {
  13876. return this._isReady;
  13877. };
  13878. /**
  13879. * Is this node enabled.
  13880. * 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.
  13881. * @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.
  13882. * @return {boolean} whether this node (and its parent) is enabled.
  13883. * @see setEnabled
  13884. */
  13885. Node.prototype.isEnabled = function (checkAncestors) {
  13886. if (checkAncestors === void 0) { checkAncestors = true; }
  13887. if (checkAncestors === false) {
  13888. return this._isEnabled;
  13889. }
  13890. if (this._isEnabled === false) {
  13891. return false;
  13892. }
  13893. if (this.parent !== undefined && this.parent !== null) {
  13894. return this.parent.isEnabled(checkAncestors);
  13895. }
  13896. return true;
  13897. };
  13898. /**
  13899. * Set the enabled state of this node.
  13900. * @param {boolean} value - the new enabled state
  13901. * @see isEnabled
  13902. */
  13903. Node.prototype.setEnabled = function (value) {
  13904. this._isEnabled = value;
  13905. };
  13906. /**
  13907. * Is this node a descendant of the given node.
  13908. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13909. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13910. * @see parent
  13911. */
  13912. Node.prototype.isDescendantOf = function (ancestor) {
  13913. if (this.parent) {
  13914. if (this.parent === ancestor) {
  13915. return true;
  13916. }
  13917. return this.parent.isDescendantOf(ancestor);
  13918. }
  13919. return false;
  13920. };
  13921. /**
  13922. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13923. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13924. * @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.
  13925. * @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.
  13926. */
  13927. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13928. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13929. if (!this._children) {
  13930. return;
  13931. }
  13932. for (var index = 0; index < this._children.length; index++) {
  13933. var item = this._children[index];
  13934. if (!predicate || predicate(item)) {
  13935. results.push(item);
  13936. }
  13937. if (!directDescendantsOnly) {
  13938. item._getDescendants(results, false, predicate);
  13939. }
  13940. }
  13941. };
  13942. /**
  13943. * Will return all nodes that have this node as ascendant.
  13944. * @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.
  13945. * @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.
  13946. * @return {BABYLON.Node[]} all children nodes of all types.
  13947. */
  13948. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13949. var results = new Array();
  13950. this._getDescendants(results, directDescendantsOnly, predicate);
  13951. return results;
  13952. };
  13953. /**
  13954. * Get all child-meshes of this node.
  13955. */
  13956. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13957. var results = [];
  13958. this._getDescendants(results, directDescendantsOnly, function (node) {
  13959. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13960. });
  13961. return results;
  13962. };
  13963. /**
  13964. * Get all child-transformNodes of this node.
  13965. */
  13966. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13967. var results = [];
  13968. this._getDescendants(results, directDescendantsOnly, function (node) {
  13969. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13970. });
  13971. return results;
  13972. };
  13973. /**
  13974. * Get all direct children of this node.
  13975. */
  13976. Node.prototype.getChildren = function (predicate) {
  13977. return this.getDescendants(true, predicate);
  13978. };
  13979. Node.prototype._setReady = function (state) {
  13980. if (state === this._isReady) {
  13981. return;
  13982. }
  13983. if (!state) {
  13984. this._isReady = false;
  13985. return;
  13986. }
  13987. this._isReady = true;
  13988. if (this.onReady) {
  13989. this.onReady(this);
  13990. }
  13991. };
  13992. Node.prototype.getAnimationByName = function (name) {
  13993. for (var i = 0; i < this.animations.length; i++) {
  13994. var animation = this.animations[i];
  13995. if (animation.name === name) {
  13996. return animation;
  13997. }
  13998. }
  13999. return null;
  14000. };
  14001. Node.prototype.createAnimationRange = function (name, from, to) {
  14002. // check name not already in use
  14003. if (!this._ranges[name]) {
  14004. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14005. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14006. if (this.animations[i]) {
  14007. this.animations[i].createRange(name, from, to);
  14008. }
  14009. }
  14010. }
  14011. };
  14012. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14013. if (deleteFrames === void 0) { deleteFrames = true; }
  14014. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14015. if (this.animations[i]) {
  14016. this.animations[i].deleteRange(name, deleteFrames);
  14017. }
  14018. }
  14019. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14020. };
  14021. Node.prototype.getAnimationRange = function (name) {
  14022. return this._ranges[name];
  14023. };
  14024. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14025. var range = this.getAnimationRange(name);
  14026. if (!range) {
  14027. return;
  14028. }
  14029. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14030. };
  14031. Node.prototype.serializeAnimationRanges = function () {
  14032. var serializationRanges = [];
  14033. for (var name in this._ranges) {
  14034. var localRange = this._ranges[name];
  14035. if (!localRange) {
  14036. continue;
  14037. }
  14038. var range = {};
  14039. range.name = name;
  14040. range.from = localRange.from;
  14041. range.to = localRange.to;
  14042. serializationRanges.push(range);
  14043. }
  14044. return serializationRanges;
  14045. };
  14046. // override it in derived class
  14047. Node.prototype.computeWorldMatrix = function (force) {
  14048. return BABYLON.Matrix.Identity();
  14049. };
  14050. Node.prototype.dispose = function () {
  14051. this.parent = null;
  14052. // Callback
  14053. this.onDisposeObservable.notifyObservers(this);
  14054. this.onDisposeObservable.clear();
  14055. // Behaviors
  14056. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14057. var behavior = _a[_i];
  14058. behavior.detach();
  14059. }
  14060. this._behaviors = [];
  14061. };
  14062. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14063. if (parsedNode.ranges) {
  14064. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14065. var data = parsedNode.ranges[index];
  14066. node.createAnimationRange(data.name, data.from, data.to);
  14067. }
  14068. }
  14069. };
  14070. __decorate([
  14071. BABYLON.serialize()
  14072. ], Node.prototype, "name", void 0);
  14073. __decorate([
  14074. BABYLON.serialize()
  14075. ], Node.prototype, "id", void 0);
  14076. __decorate([
  14077. BABYLON.serialize()
  14078. ], Node.prototype, "uniqueId", void 0);
  14079. __decorate([
  14080. BABYLON.serialize()
  14081. ], Node.prototype, "state", void 0);
  14082. __decorate([
  14083. BABYLON.serialize()
  14084. ], Node.prototype, "metadata", void 0);
  14085. return Node;
  14086. }());
  14087. BABYLON.Node = Node;
  14088. })(BABYLON || (BABYLON = {}));
  14089. //# sourceMappingURL=babylon.node.js.map
  14090. var BABYLON;
  14091. (function (BABYLON) {
  14092. var BoundingSphere = /** @class */ (function () {
  14093. function BoundingSphere(minimum, maximum) {
  14094. this.minimum = minimum;
  14095. this.maximum = maximum;
  14096. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14097. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14098. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14099. this.radius = distance * 0.5;
  14100. this.centerWorld = BABYLON.Vector3.Zero();
  14101. this._update(BABYLON.Matrix.Identity());
  14102. }
  14103. // Methods
  14104. BoundingSphere.prototype._update = function (world) {
  14105. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14106. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14107. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14108. };
  14109. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14110. for (var i = 0; i < 6; i++) {
  14111. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14112. return false;
  14113. }
  14114. return true;
  14115. };
  14116. BoundingSphere.prototype.intersectsPoint = function (point) {
  14117. var x = this.centerWorld.x - point.x;
  14118. var y = this.centerWorld.y - point.y;
  14119. var z = this.centerWorld.z - point.z;
  14120. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14121. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14122. return false;
  14123. return true;
  14124. };
  14125. // Statics
  14126. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14127. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14128. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14129. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14130. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14131. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14132. return false;
  14133. return true;
  14134. };
  14135. return BoundingSphere;
  14136. }());
  14137. BABYLON.BoundingSphere = BoundingSphere;
  14138. })(BABYLON || (BABYLON = {}));
  14139. //# sourceMappingURL=babylon.boundingSphere.js.map
  14140. var BABYLON;
  14141. (function (BABYLON) {
  14142. var BoundingBox = /** @class */ (function () {
  14143. function BoundingBox(minimum, maximum) {
  14144. this.minimum = minimum;
  14145. this.maximum = maximum;
  14146. this.vectors = new Array();
  14147. this.vectorsWorld = new Array();
  14148. // Bounding vectors
  14149. this.vectors.push(this.minimum.clone());
  14150. this.vectors.push(this.maximum.clone());
  14151. this.vectors.push(this.minimum.clone());
  14152. this.vectors[2].x = this.maximum.x;
  14153. this.vectors.push(this.minimum.clone());
  14154. this.vectors[3].y = this.maximum.y;
  14155. this.vectors.push(this.minimum.clone());
  14156. this.vectors[4].z = this.maximum.z;
  14157. this.vectors.push(this.maximum.clone());
  14158. this.vectors[5].z = this.minimum.z;
  14159. this.vectors.push(this.maximum.clone());
  14160. this.vectors[6].x = this.minimum.x;
  14161. this.vectors.push(this.maximum.clone());
  14162. this.vectors[7].y = this.minimum.y;
  14163. // OBB
  14164. this.center = this.maximum.add(this.minimum).scale(0.5);
  14165. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14166. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14167. // World
  14168. for (var index = 0; index < this.vectors.length; index++) {
  14169. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14170. }
  14171. this.minimumWorld = BABYLON.Vector3.Zero();
  14172. this.maximumWorld = BABYLON.Vector3.Zero();
  14173. this.centerWorld = BABYLON.Vector3.Zero();
  14174. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14175. this._update(BABYLON.Matrix.Identity());
  14176. }
  14177. // Methods
  14178. BoundingBox.prototype.getWorldMatrix = function () {
  14179. return this._worldMatrix;
  14180. };
  14181. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14182. this._worldMatrix.copyFrom(matrix);
  14183. return this;
  14184. };
  14185. BoundingBox.prototype._update = function (world) {
  14186. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14187. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14188. for (var index = 0; index < this.vectors.length; index++) {
  14189. var v = this.vectorsWorld[index];
  14190. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14191. if (v.x < this.minimumWorld.x)
  14192. this.minimumWorld.x = v.x;
  14193. if (v.y < this.minimumWorld.y)
  14194. this.minimumWorld.y = v.y;
  14195. if (v.z < this.minimumWorld.z)
  14196. this.minimumWorld.z = v.z;
  14197. if (v.x > this.maximumWorld.x)
  14198. this.maximumWorld.x = v.x;
  14199. if (v.y > this.maximumWorld.y)
  14200. this.maximumWorld.y = v.y;
  14201. if (v.z > this.maximumWorld.z)
  14202. this.maximumWorld.z = v.z;
  14203. }
  14204. // Extend
  14205. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14206. this.extendSizeWorld.scaleInPlace(0.5);
  14207. // OBB
  14208. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14209. this.centerWorld.scaleInPlace(0.5);
  14210. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14211. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14212. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14213. this._worldMatrix = world;
  14214. };
  14215. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14216. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14217. };
  14218. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14219. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14220. };
  14221. BoundingBox.prototype.intersectsPoint = function (point) {
  14222. var delta = -BABYLON.Epsilon;
  14223. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14224. return false;
  14225. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14226. return false;
  14227. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14228. return false;
  14229. return true;
  14230. };
  14231. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14232. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14233. };
  14234. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14235. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14236. return false;
  14237. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14238. return false;
  14239. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14240. return false;
  14241. return true;
  14242. };
  14243. // Statics
  14244. BoundingBox.Intersects = function (box0, box1) {
  14245. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14246. return false;
  14247. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14248. return false;
  14249. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14250. return false;
  14251. return true;
  14252. };
  14253. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14254. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14255. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14256. return (num <= (sphereRadius * sphereRadius));
  14257. };
  14258. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14259. for (var p = 0; p < 6; p++) {
  14260. for (var i = 0; i < 8; i++) {
  14261. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14262. return false;
  14263. }
  14264. }
  14265. }
  14266. return true;
  14267. };
  14268. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14269. for (var p = 0; p < 6; p++) {
  14270. var inCount = 8;
  14271. for (var i = 0; i < 8; i++) {
  14272. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14273. --inCount;
  14274. }
  14275. else {
  14276. break;
  14277. }
  14278. }
  14279. if (inCount === 0)
  14280. return false;
  14281. }
  14282. return true;
  14283. };
  14284. return BoundingBox;
  14285. }());
  14286. BABYLON.BoundingBox = BoundingBox;
  14287. })(BABYLON || (BABYLON = {}));
  14288. //# sourceMappingURL=babylon.boundingBox.js.map
  14289. var BABYLON;
  14290. (function (BABYLON) {
  14291. var computeBoxExtents = function (axis, box) {
  14292. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14293. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14294. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14295. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14296. var r = r0 + r1 + r2;
  14297. return {
  14298. min: p - r,
  14299. max: p + r
  14300. };
  14301. };
  14302. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14303. var axisOverlap = function (axis, box0, box1) {
  14304. var result0 = computeBoxExtents(axis, box0);
  14305. var result1 = computeBoxExtents(axis, box1);
  14306. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14307. };
  14308. var BoundingInfo = /** @class */ (function () {
  14309. function BoundingInfo(minimum, maximum) {
  14310. this.minimum = minimum;
  14311. this.maximum = maximum;
  14312. this._isLocked = false;
  14313. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14314. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14315. }
  14316. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14317. get: function () {
  14318. return this._isLocked;
  14319. },
  14320. set: function (value) {
  14321. this._isLocked = value;
  14322. },
  14323. enumerable: true,
  14324. configurable: true
  14325. });
  14326. // Methods
  14327. BoundingInfo.prototype.update = function (world) {
  14328. if (this._isLocked) {
  14329. return;
  14330. }
  14331. this.boundingBox._update(world);
  14332. this.boundingSphere._update(world);
  14333. };
  14334. /**
  14335. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14336. * @param center New center of the bounding info
  14337. * @param extend New extend of the bounding info
  14338. */
  14339. BoundingInfo.prototype.centerOn = function (center, extend) {
  14340. this.minimum = center.subtract(extend);
  14341. this.maximum = center.add(extend);
  14342. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14343. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14344. return this;
  14345. };
  14346. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14347. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14348. return false;
  14349. return this.boundingBox.isInFrustum(frustumPlanes);
  14350. };
  14351. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14352. /**
  14353. * Gets the world distance between the min and max points of the bounding box
  14354. */
  14355. get: function () {
  14356. var boundingBox = this.boundingBox;
  14357. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14358. return size.length();
  14359. },
  14360. enumerable: true,
  14361. configurable: true
  14362. });
  14363. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14364. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14365. };
  14366. BoundingInfo.prototype._checkCollision = function (collider) {
  14367. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14368. };
  14369. BoundingInfo.prototype.intersectsPoint = function (point) {
  14370. if (!this.boundingSphere.centerWorld) {
  14371. return false;
  14372. }
  14373. if (!this.boundingSphere.intersectsPoint(point)) {
  14374. return false;
  14375. }
  14376. if (!this.boundingBox.intersectsPoint(point)) {
  14377. return false;
  14378. }
  14379. return true;
  14380. };
  14381. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14382. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14383. return false;
  14384. }
  14385. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14386. return false;
  14387. }
  14388. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14389. return false;
  14390. }
  14391. if (!precise) {
  14392. return true;
  14393. }
  14394. var box0 = this.boundingBox;
  14395. var box1 = boundingInfo.boundingBox;
  14396. if (!axisOverlap(box0.directions[0], box0, box1))
  14397. return false;
  14398. if (!axisOverlap(box0.directions[1], box0, box1))
  14399. return false;
  14400. if (!axisOverlap(box0.directions[2], box0, box1))
  14401. return false;
  14402. if (!axisOverlap(box1.directions[0], box0, box1))
  14403. return false;
  14404. if (!axisOverlap(box1.directions[1], box0, box1))
  14405. return false;
  14406. if (!axisOverlap(box1.directions[2], box0, box1))
  14407. return false;
  14408. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14409. return false;
  14410. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14411. return false;
  14412. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14413. return false;
  14414. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14415. return false;
  14416. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14417. return false;
  14418. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14419. return false;
  14420. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14421. return false;
  14422. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14423. return false;
  14424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14425. return false;
  14426. return true;
  14427. };
  14428. return BoundingInfo;
  14429. }());
  14430. BABYLON.BoundingInfo = BoundingInfo;
  14431. })(BABYLON || (BABYLON = {}));
  14432. //# sourceMappingURL=babylon.boundingInfo.js.map
  14433. var BABYLON;
  14434. (function (BABYLON) {
  14435. var TransformNode = /** @class */ (function (_super) {
  14436. __extends(TransformNode, _super);
  14437. function TransformNode(name, scene, isPure) {
  14438. if (scene === void 0) { scene = null; }
  14439. if (isPure === void 0) { isPure = true; }
  14440. var _this = _super.call(this, name, scene) || this;
  14441. // Properties
  14442. _this._rotation = BABYLON.Vector3.Zero();
  14443. _this._scaling = BABYLON.Vector3.One();
  14444. _this._isDirty = false;
  14445. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14446. _this.scalingDeterminant = 1;
  14447. _this.infiniteDistance = false;
  14448. _this.position = BABYLON.Vector3.Zero();
  14449. _this._localWorld = BABYLON.Matrix.Zero();
  14450. _this._worldMatrix = BABYLON.Matrix.Zero();
  14451. _this._worldMatrixDeterminant = 0;
  14452. _this._absolutePosition = BABYLON.Vector3.Zero();
  14453. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14454. _this._postMultiplyPivotMatrix = false;
  14455. _this._isWorldMatrixFrozen = false;
  14456. /**
  14457. * An event triggered after the world matrix is updated
  14458. * @type {BABYLON.Observable}
  14459. */
  14460. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14461. _this._nonUniformScaling = false;
  14462. if (isPure) {
  14463. _this.getScene().addTransformNode(_this);
  14464. }
  14465. return _this;
  14466. }
  14467. Object.defineProperty(TransformNode.prototype, "rotation", {
  14468. /**
  14469. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14470. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14471. * Default : (0.0, 0.0, 0.0)
  14472. */
  14473. get: function () {
  14474. return this._rotation;
  14475. },
  14476. set: function (newRotation) {
  14477. this._rotation = newRotation;
  14478. },
  14479. enumerable: true,
  14480. configurable: true
  14481. });
  14482. Object.defineProperty(TransformNode.prototype, "scaling", {
  14483. /**
  14484. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14485. * Default : (1.0, 1.0, 1.0)
  14486. */
  14487. get: function () {
  14488. return this._scaling;
  14489. },
  14490. /**
  14491. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14492. * Default : (1.0, 1.0, 1.0)
  14493. */
  14494. set: function (newScaling) {
  14495. this._scaling = newScaling;
  14496. },
  14497. enumerable: true,
  14498. configurable: true
  14499. });
  14500. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14501. /**
  14502. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14503. * It's null by default.
  14504. * 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)
  14505. */
  14506. get: function () {
  14507. return this._rotationQuaternion;
  14508. },
  14509. set: function (quaternion) {
  14510. this._rotationQuaternion = quaternion;
  14511. //reset the rotation vector.
  14512. if (quaternion && this.rotation.length()) {
  14513. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14514. }
  14515. },
  14516. enumerable: true,
  14517. configurable: true
  14518. });
  14519. /**
  14520. * Returns the latest update of the World matrix
  14521. * Returns a Matrix.
  14522. */
  14523. TransformNode.prototype.getWorldMatrix = function () {
  14524. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14525. this.computeWorldMatrix();
  14526. }
  14527. return this._worldMatrix;
  14528. };
  14529. /**
  14530. * Returns the latest update of the World matrix determinant.
  14531. */
  14532. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14533. return this._worldMatrixDeterminant;
  14534. };
  14535. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14536. /**
  14537. * Returns directly the latest state of the mesh World matrix.
  14538. * A Matrix is returned.
  14539. */
  14540. get: function () {
  14541. return this._worldMatrix;
  14542. },
  14543. enumerable: true,
  14544. configurable: true
  14545. });
  14546. /**
  14547. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14548. * Returns the AbstractMesh.
  14549. */
  14550. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14551. this._poseMatrix.copyFrom(matrix);
  14552. return this;
  14553. };
  14554. /**
  14555. * Returns the mesh Pose matrix.
  14556. * Returned object : Matrix
  14557. */
  14558. TransformNode.prototype.getPoseMatrix = function () {
  14559. return this._poseMatrix;
  14560. };
  14561. TransformNode.prototype._isSynchronized = function () {
  14562. if (this._isDirty) {
  14563. return false;
  14564. }
  14565. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14566. return false;
  14567. if (this._cache.pivotMatrixUpdated) {
  14568. return false;
  14569. }
  14570. if (this.infiniteDistance) {
  14571. return false;
  14572. }
  14573. if (!this._cache.position.equals(this.position))
  14574. return false;
  14575. if (this.rotationQuaternion) {
  14576. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14577. return false;
  14578. }
  14579. if (!this._cache.rotation.equals(this.rotation))
  14580. return false;
  14581. if (!this._cache.scaling.equals(this.scaling))
  14582. return false;
  14583. return true;
  14584. };
  14585. TransformNode.prototype._initCache = function () {
  14586. _super.prototype._initCache.call(this);
  14587. this._cache.localMatrixUpdated = false;
  14588. this._cache.position = BABYLON.Vector3.Zero();
  14589. this._cache.scaling = BABYLON.Vector3.Zero();
  14590. this._cache.rotation = BABYLON.Vector3.Zero();
  14591. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14592. this._cache.billboardMode = -1;
  14593. };
  14594. TransformNode.prototype.markAsDirty = function (property) {
  14595. if (property === "rotation") {
  14596. this.rotationQuaternion = null;
  14597. }
  14598. this._currentRenderId = Number.MAX_VALUE;
  14599. this._isDirty = true;
  14600. return this;
  14601. };
  14602. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14603. /**
  14604. * Returns the current mesh absolute position.
  14605. * Retuns a Vector3.
  14606. */
  14607. get: function () {
  14608. return this._absolutePosition;
  14609. },
  14610. enumerable: true,
  14611. configurable: true
  14612. });
  14613. /**
  14614. * Sets a new pivot matrix to the mesh.
  14615. * Returns the AbstractMesh.
  14616. */
  14617. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14618. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14619. this._pivotMatrix = matrix.clone();
  14620. this._cache.pivotMatrixUpdated = true;
  14621. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14622. if (this._postMultiplyPivotMatrix) {
  14623. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14624. }
  14625. return this;
  14626. };
  14627. /**
  14628. * Returns the mesh pivot matrix.
  14629. * Default : Identity.
  14630. * A Matrix is returned.
  14631. */
  14632. TransformNode.prototype.getPivotMatrix = function () {
  14633. return this._pivotMatrix;
  14634. };
  14635. /**
  14636. * Prevents the World matrix to be computed any longer.
  14637. * Returns the AbstractMesh.
  14638. */
  14639. TransformNode.prototype.freezeWorldMatrix = function () {
  14640. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14641. this.computeWorldMatrix(true);
  14642. this._isWorldMatrixFrozen = true;
  14643. return this;
  14644. };
  14645. /**
  14646. * Allows back the World matrix computation.
  14647. * Returns the AbstractMesh.
  14648. */
  14649. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14650. this._isWorldMatrixFrozen = false;
  14651. this.computeWorldMatrix(true);
  14652. return this;
  14653. };
  14654. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14655. /**
  14656. * True if the World matrix has been frozen.
  14657. * Returns a boolean.
  14658. */
  14659. get: function () {
  14660. return this._isWorldMatrixFrozen;
  14661. },
  14662. enumerable: true,
  14663. configurable: true
  14664. });
  14665. /**
  14666. * Retuns the mesh absolute position in the World.
  14667. * Returns a Vector3.
  14668. */
  14669. TransformNode.prototype.getAbsolutePosition = function () {
  14670. this.computeWorldMatrix();
  14671. return this._absolutePosition;
  14672. };
  14673. /**
  14674. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14675. * Returns the AbstractMesh.
  14676. */
  14677. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14678. if (!absolutePosition) {
  14679. return this;
  14680. }
  14681. var absolutePositionX;
  14682. var absolutePositionY;
  14683. var absolutePositionZ;
  14684. if (absolutePosition.x === undefined) {
  14685. if (arguments.length < 3) {
  14686. return this;
  14687. }
  14688. absolutePositionX = arguments[0];
  14689. absolutePositionY = arguments[1];
  14690. absolutePositionZ = arguments[2];
  14691. }
  14692. else {
  14693. absolutePositionX = absolutePosition.x;
  14694. absolutePositionY = absolutePosition.y;
  14695. absolutePositionZ = absolutePosition.z;
  14696. }
  14697. if (this.parent) {
  14698. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14699. invertParentWorldMatrix.invert();
  14700. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14701. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14702. }
  14703. else {
  14704. this.position.x = absolutePositionX;
  14705. this.position.y = absolutePositionY;
  14706. this.position.z = absolutePositionZ;
  14707. }
  14708. return this;
  14709. };
  14710. /**
  14711. * Sets the mesh position in its local space.
  14712. * Returns the AbstractMesh.
  14713. */
  14714. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14715. this.computeWorldMatrix();
  14716. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14717. return this;
  14718. };
  14719. /**
  14720. * Returns the mesh position in the local space from the current World matrix values.
  14721. * Returns a new Vector3.
  14722. */
  14723. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14724. this.computeWorldMatrix();
  14725. var invLocalWorldMatrix = this._localWorld.clone();
  14726. invLocalWorldMatrix.invert();
  14727. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14728. };
  14729. /**
  14730. * Translates the mesh along the passed Vector3 in its local space.
  14731. * Returns the AbstractMesh.
  14732. */
  14733. TransformNode.prototype.locallyTranslate = function (vector3) {
  14734. this.computeWorldMatrix(true);
  14735. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14736. return this;
  14737. };
  14738. /**
  14739. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14740. * @param targetPoint the position (must be in same space as current mesh) to look at
  14741. * @param yawCor optional yaw (y-axis) correction in radians
  14742. * @param pitchCor optional pitch (x-axis) correction in radians
  14743. * @param rollCor optional roll (z-axis) correction in radians
  14744. * @param space the choosen space of the target
  14745. * @returns the TransformNode.
  14746. */
  14747. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14748. if (yawCor === void 0) { yawCor = 0; }
  14749. if (pitchCor === void 0) { pitchCor = 0; }
  14750. if (rollCor === void 0) { rollCor = 0; }
  14751. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14752. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14753. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14754. targetPoint.subtractToRef(pos, dv);
  14755. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14756. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14757. var pitch = Math.atan2(dv.y, len);
  14758. if (this.rotationQuaternion) {
  14759. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14760. }
  14761. else {
  14762. this.rotation.x = pitch + pitchCor;
  14763. this.rotation.y = yaw + yawCor;
  14764. this.rotation.z = rollCor;
  14765. }
  14766. return this;
  14767. };
  14768. /**
  14769. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14770. * This Vector3 is expressed in the World space.
  14771. */
  14772. TransformNode.prototype.getDirection = function (localAxis) {
  14773. var result = BABYLON.Vector3.Zero();
  14774. this.getDirectionToRef(localAxis, result);
  14775. return result;
  14776. };
  14777. /**
  14778. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14779. * localAxis is expressed in the mesh local space.
  14780. * result is computed in the Wordl space from the mesh World matrix.
  14781. * Returns the AbstractMesh.
  14782. */
  14783. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14784. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14785. return this;
  14786. };
  14787. TransformNode.prototype.setPivotPoint = function (point, space) {
  14788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14789. if (this.getScene().getRenderId() == 0) {
  14790. this.computeWorldMatrix(true);
  14791. }
  14792. var wm = this.getWorldMatrix();
  14793. if (space == BABYLON.Space.WORLD) {
  14794. var tmat = BABYLON.Tmp.Matrix[0];
  14795. wm.invertToRef(tmat);
  14796. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14797. }
  14798. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14799. this._pivotMatrix.m[12] = -point.x;
  14800. this._pivotMatrix.m[13] = -point.y;
  14801. this._pivotMatrix.m[14] = -point.z;
  14802. this._cache.pivotMatrixUpdated = true;
  14803. return this;
  14804. };
  14805. /**
  14806. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14807. */
  14808. TransformNode.prototype.getPivotPoint = function () {
  14809. var point = BABYLON.Vector3.Zero();
  14810. this.getPivotPointToRef(point);
  14811. return point;
  14812. };
  14813. /**
  14814. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14815. * Returns the AbstractMesh.
  14816. */
  14817. TransformNode.prototype.getPivotPointToRef = function (result) {
  14818. result.x = -this._pivotMatrix.m[12];
  14819. result.y = -this._pivotMatrix.m[13];
  14820. result.z = -this._pivotMatrix.m[14];
  14821. return this;
  14822. };
  14823. /**
  14824. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14825. */
  14826. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14827. var point = BABYLON.Vector3.Zero();
  14828. this.getAbsolutePivotPointToRef(point);
  14829. return point;
  14830. };
  14831. /**
  14832. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14833. * Returns the AbstractMesh.
  14834. */
  14835. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14836. result.x = this._pivotMatrix.m[12];
  14837. result.y = this._pivotMatrix.m[13];
  14838. result.z = this._pivotMatrix.m[14];
  14839. this.getPivotPointToRef(result);
  14840. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14841. return this;
  14842. };
  14843. /**
  14844. * Defines the passed node as the parent of the current node.
  14845. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14846. * Returns the TransformNode.
  14847. */
  14848. TransformNode.prototype.setParent = function (node) {
  14849. if (node === null) {
  14850. var rotation = BABYLON.Tmp.Quaternion[0];
  14851. var position = BABYLON.Tmp.Vector3[0];
  14852. var scale = BABYLON.Tmp.Vector3[1];
  14853. if (this.parent && this.parent.computeWorldMatrix) {
  14854. this.parent.computeWorldMatrix(true);
  14855. }
  14856. this.computeWorldMatrix(true);
  14857. this.getWorldMatrix().decompose(scale, rotation, position);
  14858. if (this.rotationQuaternion) {
  14859. this.rotationQuaternion.copyFrom(rotation);
  14860. }
  14861. else {
  14862. rotation.toEulerAnglesToRef(this.rotation);
  14863. }
  14864. this.scaling.x = scale.x;
  14865. this.scaling.y = scale.y;
  14866. this.scaling.z = scale.z;
  14867. this.position.x = position.x;
  14868. this.position.y = position.y;
  14869. this.position.z = position.z;
  14870. }
  14871. else {
  14872. var rotation = BABYLON.Tmp.Quaternion[0];
  14873. var position = BABYLON.Tmp.Vector3[0];
  14874. var scale = BABYLON.Tmp.Vector3[1];
  14875. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14876. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14877. this.computeWorldMatrix(true);
  14878. node.computeWorldMatrix(true);
  14879. node.getWorldMatrix().invertToRef(invParentMatrix);
  14880. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14881. diffMatrix.decompose(scale, rotation, position);
  14882. if (this.rotationQuaternion) {
  14883. this.rotationQuaternion.copyFrom(rotation);
  14884. }
  14885. else {
  14886. rotation.toEulerAnglesToRef(this.rotation);
  14887. }
  14888. this.position.x = position.x;
  14889. this.position.y = position.y;
  14890. this.position.z = position.z;
  14891. this.scaling.x = scale.x;
  14892. this.scaling.y = scale.y;
  14893. this.scaling.z = scale.z;
  14894. }
  14895. this.parent = node;
  14896. return this;
  14897. };
  14898. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14899. get: function () {
  14900. return this._nonUniformScaling;
  14901. },
  14902. enumerable: true,
  14903. configurable: true
  14904. });
  14905. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14906. if (this._nonUniformScaling === value) {
  14907. return false;
  14908. }
  14909. this._nonUniformScaling = true;
  14910. return true;
  14911. };
  14912. /**
  14913. * Attach the current TransformNode to another TransformNode associated with a bone
  14914. * @param bone Bone affecting the TransformNode
  14915. * @param affectedTransformNode TransformNode associated with the bone
  14916. */
  14917. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14918. this._transformToBoneReferal = affectedTransformNode;
  14919. this.parent = bone;
  14920. if (bone.getWorldMatrix().determinant() < 0) {
  14921. this.scalingDeterminant *= -1;
  14922. }
  14923. return this;
  14924. };
  14925. TransformNode.prototype.detachFromBone = function () {
  14926. if (!this.parent) {
  14927. return this;
  14928. }
  14929. if (this.parent.getWorldMatrix().determinant() < 0) {
  14930. this.scalingDeterminant *= -1;
  14931. }
  14932. this._transformToBoneReferal = null;
  14933. this.parent = null;
  14934. return this;
  14935. };
  14936. /**
  14937. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14938. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14939. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14940. * The passed axis is also normalized.
  14941. * Returns the AbstractMesh.
  14942. */
  14943. TransformNode.prototype.rotate = function (axis, amount, space) {
  14944. axis.normalize();
  14945. if (!this.rotationQuaternion) {
  14946. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14947. this.rotation = BABYLON.Vector3.Zero();
  14948. }
  14949. var rotationQuaternion;
  14950. if (!space || space === BABYLON.Space.LOCAL) {
  14951. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14952. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14953. }
  14954. else {
  14955. if (this.parent) {
  14956. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14957. invertParentWorldMatrix.invert();
  14958. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14959. }
  14960. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14961. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14962. }
  14963. return this;
  14964. };
  14965. /**
  14966. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14967. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14968. * The passed axis is also normalized.
  14969. * Returns the AbstractMesh.
  14970. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14971. */
  14972. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14973. axis.normalize();
  14974. if (!this.rotationQuaternion) {
  14975. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14976. this.rotation.copyFromFloats(0, 0, 0);
  14977. }
  14978. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14979. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14980. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14981. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14982. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14983. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14984. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14985. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14986. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14987. return this;
  14988. };
  14989. /**
  14990. * Translates the mesh along the axis vector for the passed distance in the given space.
  14991. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14992. * Returns the AbstractMesh.
  14993. */
  14994. TransformNode.prototype.translate = function (axis, distance, space) {
  14995. var displacementVector = axis.scale(distance);
  14996. if (!space || space === BABYLON.Space.LOCAL) {
  14997. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14998. this.setPositionWithLocalVector(tempV3);
  14999. }
  15000. else {
  15001. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15002. }
  15003. return this;
  15004. };
  15005. /**
  15006. * Adds a rotation step to the mesh current rotation.
  15007. * x, y, z are Euler angles expressed in radians.
  15008. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15009. * This means this rotation is made in the mesh local space only.
  15010. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15011. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15012. * ```javascript
  15013. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15014. * ```
  15015. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15016. * 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.
  15017. * Returns the AbstractMesh.
  15018. */
  15019. TransformNode.prototype.addRotation = function (x, y, z) {
  15020. var rotationQuaternion;
  15021. if (this.rotationQuaternion) {
  15022. rotationQuaternion = this.rotationQuaternion;
  15023. }
  15024. else {
  15025. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15026. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15027. }
  15028. var accumulation = BABYLON.Tmp.Quaternion[0];
  15029. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15030. rotationQuaternion.multiplyInPlace(accumulation);
  15031. if (!this.rotationQuaternion) {
  15032. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15033. }
  15034. return this;
  15035. };
  15036. /**
  15037. * Computes the mesh World matrix and returns it.
  15038. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15039. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15040. * If the parameter `force`is set to `true`, the actual computation is done.
  15041. * Returns the mesh World Matrix.
  15042. */
  15043. TransformNode.prototype.computeWorldMatrix = function (force) {
  15044. if (this._isWorldMatrixFrozen) {
  15045. return this._worldMatrix;
  15046. }
  15047. if (!force && this.isSynchronized(true)) {
  15048. return this._worldMatrix;
  15049. }
  15050. this._cache.position.copyFrom(this.position);
  15051. this._cache.scaling.copyFrom(this.scaling);
  15052. this._cache.pivotMatrixUpdated = false;
  15053. this._cache.billboardMode = this.billboardMode;
  15054. this._currentRenderId = this.getScene().getRenderId();
  15055. this._isDirty = false;
  15056. // Scaling
  15057. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15058. // Rotation
  15059. //rotate, if quaternion is set and rotation was used
  15060. if (this.rotationQuaternion) {
  15061. var len = this.rotation.length();
  15062. if (len) {
  15063. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15064. this.rotation.copyFromFloats(0, 0, 0);
  15065. }
  15066. }
  15067. if (this.rotationQuaternion) {
  15068. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15069. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15070. }
  15071. else {
  15072. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15073. this._cache.rotation.copyFrom(this.rotation);
  15074. }
  15075. // Translation
  15076. var camera = this.getScene().activeCamera;
  15077. if (this.infiniteDistance && !this.parent && camera) {
  15078. var cameraWorldMatrix = camera.getWorldMatrix();
  15079. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15080. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15081. }
  15082. else {
  15083. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15084. }
  15085. // Composing transformations
  15086. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15087. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15088. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15089. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15090. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15091. // Need to decompose each rotation here
  15092. var currentPosition = BABYLON.Tmp.Vector3[3];
  15093. if (this.parent && this.parent.getWorldMatrix) {
  15094. if (this._transformToBoneReferal) {
  15095. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15096. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15097. }
  15098. else {
  15099. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15100. }
  15101. }
  15102. else {
  15103. currentPosition.copyFrom(this.position);
  15104. }
  15105. currentPosition.subtractInPlace(camera.globalPosition);
  15106. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15107. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15108. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15109. }
  15110. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15111. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15112. }
  15113. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15114. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15115. }
  15116. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15117. }
  15118. else {
  15119. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15120. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15121. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15122. }
  15123. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15124. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15125. }
  15126. // Local world
  15127. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15128. // Parent
  15129. if (this.parent && this.parent.getWorldMatrix) {
  15130. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15131. if (this._transformToBoneReferal) {
  15132. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15133. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15134. }
  15135. else {
  15136. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15137. }
  15138. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15139. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15140. this._worldMatrix.copyFrom(this._localWorld);
  15141. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15142. }
  15143. else {
  15144. if (this._transformToBoneReferal) {
  15145. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15146. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15147. }
  15148. else {
  15149. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15150. }
  15151. }
  15152. this._markSyncedWithParent();
  15153. }
  15154. else {
  15155. this._worldMatrix.copyFrom(this._localWorld);
  15156. }
  15157. // Post multiply inverse of pivotMatrix
  15158. if (this._postMultiplyPivotMatrix) {
  15159. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15160. }
  15161. // Normal matrix
  15162. if (this.scaling.isNonUniform) {
  15163. this._updateNonUniformScalingState(true);
  15164. }
  15165. else if (this.parent && this.parent._nonUniformScaling) {
  15166. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15167. }
  15168. else {
  15169. this._updateNonUniformScalingState(false);
  15170. }
  15171. this._afterComputeWorldMatrix();
  15172. // Absolute position
  15173. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15174. // Callbacks
  15175. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15176. if (!this._poseMatrix) {
  15177. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15178. }
  15179. // Cache the determinant
  15180. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15181. return this._worldMatrix;
  15182. };
  15183. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15184. };
  15185. /**
  15186. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15187. * @param func: callback function to add
  15188. *
  15189. * Returns the TransformNode.
  15190. */
  15191. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15192. this.onAfterWorldMatrixUpdateObservable.add(func);
  15193. return this;
  15194. };
  15195. /**
  15196. * Removes a registered callback function.
  15197. * Returns the TransformNode.
  15198. */
  15199. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15200. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15201. return this;
  15202. };
  15203. /**
  15204. * Clone the current transform node
  15205. * Returns the new transform node
  15206. * @param name Name of the new clone
  15207. * @param newParent New parent for the clone
  15208. * @param doNotCloneChildren Do not clone children hierarchy
  15209. */
  15210. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15211. var _this = this;
  15212. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15213. result.name = name;
  15214. result.id = name;
  15215. if (newParent) {
  15216. result.parent = newParent;
  15217. }
  15218. if (!doNotCloneChildren) {
  15219. // Children
  15220. var directDescendants = this.getDescendants(true);
  15221. for (var index = 0; index < directDescendants.length; index++) {
  15222. var child = directDescendants[index];
  15223. if (child.clone) {
  15224. child.clone(name + "." + child.name, result);
  15225. }
  15226. }
  15227. }
  15228. return result;
  15229. };
  15230. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15231. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15232. serializationObject.type = this.getClassName();
  15233. // Parent
  15234. if (this.parent) {
  15235. serializationObject.parentId = this.parent.id;
  15236. }
  15237. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15238. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15239. }
  15240. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15241. serializationObject.isEnabled = this.isEnabled();
  15242. // Parent
  15243. if (this.parent) {
  15244. serializationObject.parentId = this.parent.id;
  15245. }
  15246. return serializationObject;
  15247. };
  15248. // Statics
  15249. /**
  15250. * Returns a new TransformNode object parsed from the source provided.
  15251. * The parameter `parsedMesh` is the source.
  15252. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15253. */
  15254. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15255. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15256. if (BABYLON.Tags) {
  15257. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15258. }
  15259. if (parsedTransformNode.localMatrix) {
  15260. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15261. }
  15262. else if (parsedTransformNode.pivotMatrix) {
  15263. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15264. }
  15265. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15266. // Parent
  15267. if (parsedTransformNode.parentId) {
  15268. transformNode._waitingParentId = parsedTransformNode.parentId;
  15269. }
  15270. return transformNode;
  15271. };
  15272. /**
  15273. * Disposes the TransformNode.
  15274. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15275. * Returns nothing.
  15276. */
  15277. TransformNode.prototype.dispose = function (doNotRecurse) {
  15278. // Animations
  15279. this.getScene().stopAnimation(this);
  15280. // Remove from scene
  15281. this.getScene().removeTransformNode(this);
  15282. if (!doNotRecurse) {
  15283. // Children
  15284. var objects = this.getDescendants(true);
  15285. for (var index = 0; index < objects.length; index++) {
  15286. objects[index].dispose();
  15287. }
  15288. }
  15289. else {
  15290. var childMeshes = this.getChildMeshes(true);
  15291. for (index = 0; index < childMeshes.length; index++) {
  15292. var child = childMeshes[index];
  15293. child.parent = null;
  15294. child.computeWorldMatrix(true);
  15295. }
  15296. }
  15297. this.onAfterWorldMatrixUpdateObservable.clear();
  15298. _super.prototype.dispose.call(this);
  15299. };
  15300. // Statics
  15301. TransformNode.BILLBOARDMODE_NONE = 0;
  15302. TransformNode.BILLBOARDMODE_X = 1;
  15303. TransformNode.BILLBOARDMODE_Y = 2;
  15304. TransformNode.BILLBOARDMODE_Z = 4;
  15305. TransformNode.BILLBOARDMODE_ALL = 7;
  15306. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15307. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15308. __decorate([
  15309. BABYLON.serializeAsVector3()
  15310. ], TransformNode.prototype, "_rotation", void 0);
  15311. __decorate([
  15312. BABYLON.serializeAsQuaternion()
  15313. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15314. __decorate([
  15315. BABYLON.serializeAsVector3()
  15316. ], TransformNode.prototype, "_scaling", void 0);
  15317. __decorate([
  15318. BABYLON.serialize()
  15319. ], TransformNode.prototype, "billboardMode", void 0);
  15320. __decorate([
  15321. BABYLON.serialize()
  15322. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15323. __decorate([
  15324. BABYLON.serialize()
  15325. ], TransformNode.prototype, "infiniteDistance", void 0);
  15326. __decorate([
  15327. BABYLON.serializeAsVector3()
  15328. ], TransformNode.prototype, "position", void 0);
  15329. return TransformNode;
  15330. }(BABYLON.Node));
  15331. BABYLON.TransformNode = TransformNode;
  15332. })(BABYLON || (BABYLON = {}));
  15333. //# sourceMappingURL=babylon.transformNode.js.map
  15334. var BABYLON;
  15335. (function (BABYLON) {
  15336. var AbstractMesh = /** @class */ (function (_super) {
  15337. __extends(AbstractMesh, _super);
  15338. // Constructor
  15339. function AbstractMesh(name, scene) {
  15340. if (scene === void 0) { scene = null; }
  15341. var _this = _super.call(this, name, scene, false) || this;
  15342. _this._facetNb = 0; // facet number
  15343. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15344. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15345. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15346. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15347. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15348. _this._subDiv = {
  15349. max: 1,
  15350. X: 1,
  15351. Y: 1,
  15352. Z: 1
  15353. };
  15354. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15355. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15356. // Events
  15357. /**
  15358. * An event triggered when this mesh collides with another one
  15359. * @type {BABYLON.Observable}
  15360. */
  15361. _this.onCollideObservable = new BABYLON.Observable();
  15362. /**
  15363. * An event triggered when the collision's position changes
  15364. * @type {BABYLON.Observable}
  15365. */
  15366. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15367. /**
  15368. * An event triggered when material is changed
  15369. * @type {BABYLON.Observable}
  15370. */
  15371. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15372. // Properties
  15373. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15374. /**
  15375. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15376. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15377. * or
  15378. * 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.
  15379. * for more info check WebGl documentations
  15380. */
  15381. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15382. /**
  15383. * 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:
  15384. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15385. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15386. * 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.
  15387. */
  15388. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15389. /**
  15390. * 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.
  15391. * The default value is -1 which means don't break the query and wait till the result.
  15392. */
  15393. _this.occlusionRetryCount = -1;
  15394. _this._occlusionInternalRetryCounter = 0;
  15395. _this._isOccluded = false;
  15396. _this._isOcclusionQueryInProgress = false;
  15397. _this.visibility = 1.0;
  15398. _this.alphaIndex = Number.MAX_VALUE;
  15399. _this.isVisible = true;
  15400. _this.isPickable = true;
  15401. _this.showBoundingBox = false;
  15402. _this.showSubMeshesBoundingBox = false;
  15403. _this.isBlocker = false;
  15404. _this.enablePointerMoveEvents = false;
  15405. _this.renderingGroupId = 0;
  15406. _this._receiveShadows = false;
  15407. _this.renderOutline = false;
  15408. _this.outlineColor = BABYLON.Color3.Red();
  15409. _this.outlineWidth = 0.02;
  15410. _this.renderOverlay = false;
  15411. _this.overlayColor = BABYLON.Color3.Red();
  15412. _this.overlayAlpha = 0.5;
  15413. _this._hasVertexAlpha = false;
  15414. _this._useVertexColors = true;
  15415. _this._computeBonesUsingShaders = true;
  15416. _this._numBoneInfluencers = 4;
  15417. _this._applyFog = true;
  15418. _this.useOctreeForRenderingSelection = true;
  15419. _this.useOctreeForPicking = true;
  15420. _this.useOctreeForCollisions = true;
  15421. _this._layerMask = 0x0FFFFFFF;
  15422. /**
  15423. * True if the mesh must be rendered in any case.
  15424. */
  15425. _this.alwaysSelectAsActiveMesh = false;
  15426. /**
  15427. * This scene's action manager
  15428. * @type {BABYLON.ActionManager}
  15429. */
  15430. _this.actionManager = null;
  15431. // Physics
  15432. _this.physicsImpostor = null;
  15433. // Collisions
  15434. _this._checkCollisions = false;
  15435. _this._collisionMask = -1;
  15436. _this._collisionGroup = -1;
  15437. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15438. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15439. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15440. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15441. // Edges
  15442. _this.edgesWidth = 1;
  15443. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15444. // Cache
  15445. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15446. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15447. _this._isDisposed = false;
  15448. _this._renderId = 0;
  15449. _this._intersectionsInProgress = new Array();
  15450. _this._unIndexed = false;
  15451. _this._lightSources = new Array();
  15452. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15453. if (collidedMesh === void 0) { collidedMesh = null; }
  15454. //TODO move this to the collision coordinator!
  15455. if (_this.getScene().workerCollisions)
  15456. newPosition.multiplyInPlace(_this._collider._radius);
  15457. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15458. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15459. _this.position.addInPlace(_this._diffPositionForCollisions);
  15460. }
  15461. if (collidedMesh) {
  15462. _this.onCollideObservable.notifyObservers(collidedMesh);
  15463. }
  15464. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15465. };
  15466. _this.getScene().addMesh(_this);
  15467. _this._resyncLightSources();
  15468. return _this;
  15469. }
  15470. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15471. get: function () {
  15472. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15473. },
  15474. enumerable: true,
  15475. configurable: true
  15476. });
  15477. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15478. get: function () {
  15479. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15480. },
  15481. enumerable: true,
  15482. configurable: true
  15483. });
  15484. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15485. get: function () {
  15486. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15487. },
  15488. enumerable: true,
  15489. configurable: true
  15490. });
  15491. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15492. get: function () {
  15493. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15494. },
  15495. enumerable: true,
  15496. configurable: true
  15497. });
  15498. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15499. get: function () {
  15500. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15501. },
  15502. enumerable: true,
  15503. configurable: true
  15504. });
  15505. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15506. /**
  15507. * Read-only : the number of facets in the mesh
  15508. */
  15509. get: function () {
  15510. return this._facetNb;
  15511. },
  15512. enumerable: true,
  15513. configurable: true
  15514. });
  15515. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15516. /**
  15517. * The number (integer) of subdivisions per axis in the partioning space
  15518. */
  15519. get: function () {
  15520. return this._partitioningSubdivisions;
  15521. },
  15522. set: function (nb) {
  15523. this._partitioningSubdivisions = nb;
  15524. },
  15525. enumerable: true,
  15526. configurable: true
  15527. });
  15528. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15529. /**
  15530. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15531. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15532. */
  15533. get: function () {
  15534. return this._partitioningBBoxRatio;
  15535. },
  15536. set: function (ratio) {
  15537. this._partitioningBBoxRatio = ratio;
  15538. },
  15539. enumerable: true,
  15540. configurable: true
  15541. });
  15542. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15543. /**
  15544. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15545. * Works only for updatable meshes.
  15546. * Doesn't work with multi-materials.
  15547. */
  15548. get: function () {
  15549. return this._facetDepthSort;
  15550. },
  15551. set: function (sort) {
  15552. this._facetDepthSort = sort;
  15553. },
  15554. enumerable: true,
  15555. configurable: true
  15556. });
  15557. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15558. /**
  15559. * The location (Vector3) where the facet depth sort must be computed from.
  15560. * By default, the active camera position.
  15561. * Used only when facet depth sort is enabled.
  15562. */
  15563. get: function () {
  15564. return this._facetDepthSortFrom;
  15565. },
  15566. set: function (location) {
  15567. this._facetDepthSortFrom = location;
  15568. },
  15569. enumerable: true,
  15570. configurable: true
  15571. });
  15572. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15573. /**
  15574. * Read-only boolean : is the feature facetData enabled ?
  15575. */
  15576. get: function () {
  15577. return this._facetDataEnabled;
  15578. },
  15579. enumerable: true,
  15580. configurable: true
  15581. });
  15582. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15583. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15584. return false;
  15585. }
  15586. this._markSubMeshesAsMiscDirty();
  15587. return true;
  15588. };
  15589. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15590. set: function (callback) {
  15591. if (this._onCollideObserver) {
  15592. this.onCollideObservable.remove(this._onCollideObserver);
  15593. }
  15594. this._onCollideObserver = this.onCollideObservable.add(callback);
  15595. },
  15596. enumerable: true,
  15597. configurable: true
  15598. });
  15599. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15600. set: function (callback) {
  15601. if (this._onCollisionPositionChangeObserver) {
  15602. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15603. }
  15604. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15605. },
  15606. enumerable: true,
  15607. configurable: true
  15608. });
  15609. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15610. /**
  15611. * 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.
  15612. */
  15613. get: function () {
  15614. return this._isOccluded;
  15615. },
  15616. set: function (value) {
  15617. this._isOccluded = value;
  15618. },
  15619. enumerable: true,
  15620. configurable: true
  15621. });
  15622. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15623. /**
  15624. * Flag to check the progress status of the query
  15625. */
  15626. get: function () {
  15627. return this._isOcclusionQueryInProgress;
  15628. },
  15629. enumerable: true,
  15630. configurable: true
  15631. });
  15632. Object.defineProperty(AbstractMesh.prototype, "material", {
  15633. get: function () {
  15634. return this._material;
  15635. },
  15636. set: function (value) {
  15637. if (this._material === value) {
  15638. return;
  15639. }
  15640. this._material = value;
  15641. if (this.onMaterialChangedObservable.hasObservers) {
  15642. this.onMaterialChangedObservable.notifyObservers(this);
  15643. }
  15644. if (!this.subMeshes) {
  15645. return;
  15646. }
  15647. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15648. var subMesh = _a[_i];
  15649. subMesh.setEffect(null);
  15650. }
  15651. },
  15652. enumerable: true,
  15653. configurable: true
  15654. });
  15655. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15656. get: function () {
  15657. return this._receiveShadows;
  15658. },
  15659. set: function (value) {
  15660. if (this._receiveShadows === value) {
  15661. return;
  15662. }
  15663. this._receiveShadows = value;
  15664. this._markSubMeshesAsLightDirty();
  15665. },
  15666. enumerable: true,
  15667. configurable: true
  15668. });
  15669. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15670. get: function () {
  15671. return this._hasVertexAlpha;
  15672. },
  15673. set: function (value) {
  15674. if (this._hasVertexAlpha === value) {
  15675. return;
  15676. }
  15677. this._hasVertexAlpha = value;
  15678. this._markSubMeshesAsAttributesDirty();
  15679. },
  15680. enumerable: true,
  15681. configurable: true
  15682. });
  15683. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15684. get: function () {
  15685. return this._useVertexColors;
  15686. },
  15687. set: function (value) {
  15688. if (this._useVertexColors === value) {
  15689. return;
  15690. }
  15691. this._useVertexColors = value;
  15692. this._markSubMeshesAsAttributesDirty();
  15693. },
  15694. enumerable: true,
  15695. configurable: true
  15696. });
  15697. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15698. get: function () {
  15699. return this._computeBonesUsingShaders;
  15700. },
  15701. set: function (value) {
  15702. if (this._computeBonesUsingShaders === value) {
  15703. return;
  15704. }
  15705. this._computeBonesUsingShaders = value;
  15706. this._markSubMeshesAsAttributesDirty();
  15707. },
  15708. enumerable: true,
  15709. configurable: true
  15710. });
  15711. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15712. get: function () {
  15713. return this._numBoneInfluencers;
  15714. },
  15715. set: function (value) {
  15716. if (this._numBoneInfluencers === value) {
  15717. return;
  15718. }
  15719. this._numBoneInfluencers = value;
  15720. this._markSubMeshesAsAttributesDirty();
  15721. },
  15722. enumerable: true,
  15723. configurable: true
  15724. });
  15725. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15726. get: function () {
  15727. return this._applyFog;
  15728. },
  15729. set: function (value) {
  15730. if (this._applyFog === value) {
  15731. return;
  15732. }
  15733. this._applyFog = value;
  15734. this._markSubMeshesAsMiscDirty();
  15735. },
  15736. enumerable: true,
  15737. configurable: true
  15738. });
  15739. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15740. get: function () {
  15741. return this._layerMask;
  15742. },
  15743. set: function (value) {
  15744. if (value === this._layerMask) {
  15745. return;
  15746. }
  15747. this._layerMask = value;
  15748. this._resyncLightSources();
  15749. },
  15750. enumerable: true,
  15751. configurable: true
  15752. });
  15753. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15754. get: function () {
  15755. return this._collisionMask;
  15756. },
  15757. set: function (mask) {
  15758. this._collisionMask = !isNaN(mask) ? mask : -1;
  15759. },
  15760. enumerable: true,
  15761. configurable: true
  15762. });
  15763. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15764. get: function () {
  15765. return this._collisionGroup;
  15766. },
  15767. set: function (mask) {
  15768. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15769. },
  15770. enumerable: true,
  15771. configurable: true
  15772. });
  15773. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15774. get: function () {
  15775. return null;
  15776. },
  15777. enumerable: true,
  15778. configurable: true
  15779. });
  15780. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15781. get: function () {
  15782. return this._skeleton;
  15783. },
  15784. set: function (value) {
  15785. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15786. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15787. }
  15788. if (value && value.needInitialSkinMatrix) {
  15789. value._registerMeshWithPoseMatrix(this);
  15790. }
  15791. this._skeleton = value;
  15792. if (!this._skeleton) {
  15793. this._bonesTransformMatrices = null;
  15794. }
  15795. this._markSubMeshesAsAttributesDirty();
  15796. },
  15797. enumerable: true,
  15798. configurable: true
  15799. });
  15800. /**
  15801. * Boolean : true if the mesh has been disposed.
  15802. */
  15803. AbstractMesh.prototype.isDisposed = function () {
  15804. return this._isDisposed;
  15805. };
  15806. /**
  15807. * Returns the string "AbstractMesh"
  15808. */
  15809. AbstractMesh.prototype.getClassName = function () {
  15810. return "AbstractMesh";
  15811. };
  15812. /**
  15813. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15814. */
  15815. AbstractMesh.prototype.toString = function (fullDetails) {
  15816. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15817. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15818. if (this._skeleton) {
  15819. ret += ", skeleton: " + this._skeleton.name;
  15820. }
  15821. if (fullDetails) {
  15822. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15823. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15824. }
  15825. return ret;
  15826. };
  15827. AbstractMesh.prototype._rebuild = function () {
  15828. if (this._occlusionQuery) {
  15829. this._occlusionQuery = null;
  15830. }
  15831. if (this._edgesRenderer) {
  15832. this._edgesRenderer._rebuild();
  15833. }
  15834. if (!this.subMeshes) {
  15835. return;
  15836. }
  15837. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15838. var subMesh = _a[_i];
  15839. subMesh._rebuild();
  15840. }
  15841. };
  15842. AbstractMesh.prototype._resyncLightSources = function () {
  15843. this._lightSources.length = 0;
  15844. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15845. var light = _a[_i];
  15846. if (!light.isEnabled()) {
  15847. continue;
  15848. }
  15849. if (light.canAffectMesh(this)) {
  15850. this._lightSources.push(light);
  15851. }
  15852. }
  15853. this._markSubMeshesAsLightDirty();
  15854. };
  15855. AbstractMesh.prototype._resyncLighSource = function (light) {
  15856. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15857. var index = this._lightSources.indexOf(light);
  15858. if (index === -1) {
  15859. if (!isIn) {
  15860. return;
  15861. }
  15862. this._lightSources.push(light);
  15863. }
  15864. else {
  15865. if (isIn) {
  15866. return;
  15867. }
  15868. this._lightSources.splice(index, 1);
  15869. }
  15870. this._markSubMeshesAsLightDirty();
  15871. };
  15872. AbstractMesh.prototype._removeLightSource = function (light) {
  15873. var index = this._lightSources.indexOf(light);
  15874. if (index === -1) {
  15875. return;
  15876. }
  15877. this._lightSources.splice(index, 1);
  15878. this._markSubMeshesAsLightDirty();
  15879. };
  15880. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15881. if (!this.subMeshes) {
  15882. return;
  15883. }
  15884. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15885. var subMesh = _a[_i];
  15886. if (subMesh._materialDefines) {
  15887. func(subMesh._materialDefines);
  15888. }
  15889. }
  15890. };
  15891. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15892. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15893. };
  15894. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15895. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15896. };
  15897. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15898. if (!this.subMeshes) {
  15899. return;
  15900. }
  15901. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15902. var subMesh = _a[_i];
  15903. var material = subMesh.getMaterial();
  15904. if (material) {
  15905. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15906. }
  15907. }
  15908. };
  15909. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15910. /**
  15911. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15912. * Default : (1.0, 1.0, 1.0)
  15913. */
  15914. get: function () {
  15915. return this._scaling;
  15916. },
  15917. /**
  15918. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15919. * Default : (1.0, 1.0, 1.0)
  15920. */
  15921. set: function (newScaling) {
  15922. this._scaling = newScaling;
  15923. if (this.physicsImpostor) {
  15924. this.physicsImpostor.forceUpdate();
  15925. }
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. // Methods
  15931. /**
  15932. * Disables the mesh edger rendering mode.
  15933. * Returns the AbstractMesh.
  15934. */
  15935. AbstractMesh.prototype.disableEdgesRendering = function () {
  15936. if (this._edgesRenderer) {
  15937. this._edgesRenderer.dispose();
  15938. this._edgesRenderer = null;
  15939. }
  15940. return this;
  15941. };
  15942. /**
  15943. * Enables the edge rendering mode on the mesh.
  15944. * This mode makes the mesh edges visible.
  15945. * Returns the AbstractMesh.
  15946. */
  15947. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15948. if (epsilon === void 0) { epsilon = 0.95; }
  15949. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15950. this.disableEdgesRendering();
  15951. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15952. return this;
  15953. };
  15954. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15955. /**
  15956. * Returns true if the mesh is blocked. Used by the class Mesh.
  15957. * Returns the boolean `false` by default.
  15958. */
  15959. get: function () {
  15960. return false;
  15961. },
  15962. enumerable: true,
  15963. configurable: true
  15964. });
  15965. /**
  15966. * Returns the mesh itself by default, used by the class Mesh.
  15967. * Returned type : AbstractMesh
  15968. */
  15969. AbstractMesh.prototype.getLOD = function (camera) {
  15970. return this;
  15971. };
  15972. /**
  15973. * Returns 0 by default, used by the class Mesh.
  15974. * Returns an integer.
  15975. */
  15976. AbstractMesh.prototype.getTotalVertices = function () {
  15977. return 0;
  15978. };
  15979. /**
  15980. * Returns null by default, used by the class Mesh.
  15981. * Returned type : integer array
  15982. */
  15983. AbstractMesh.prototype.getIndices = function () {
  15984. return null;
  15985. };
  15986. /**
  15987. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15988. * Returned type : float array or Float32Array
  15989. */
  15990. AbstractMesh.prototype.getVerticesData = function (kind) {
  15991. return null;
  15992. };
  15993. /**
  15994. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15995. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15996. * The `data` are either a numeric array either a Float32Array.
  15997. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15998. * 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).
  15999. * Note that a new underlying VertexBuffer object is created each call.
  16000. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16001. *
  16002. * Possible `kind` values :
  16003. * - BABYLON.VertexBuffer.PositionKind
  16004. * - BABYLON.VertexBuffer.UVKind
  16005. * - BABYLON.VertexBuffer.UV2Kind
  16006. * - BABYLON.VertexBuffer.UV3Kind
  16007. * - BABYLON.VertexBuffer.UV4Kind
  16008. * - BABYLON.VertexBuffer.UV5Kind
  16009. * - BABYLON.VertexBuffer.UV6Kind
  16010. * - BABYLON.VertexBuffer.ColorKind
  16011. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16012. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16013. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16014. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16015. *
  16016. * Returns the Mesh.
  16017. */
  16018. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16019. return this;
  16020. };
  16021. /**
  16022. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16023. * If the mesh has no geometry, it is simply returned as it is.
  16024. * The `data` are either a numeric array either a Float32Array.
  16025. * No new underlying VertexBuffer object is created.
  16026. * 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.
  16027. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16028. *
  16029. * Possible `kind` values :
  16030. * - BABYLON.VertexBuffer.PositionKind
  16031. * - BABYLON.VertexBuffer.UVKind
  16032. * - BABYLON.VertexBuffer.UV2Kind
  16033. * - BABYLON.VertexBuffer.UV3Kind
  16034. * - BABYLON.VertexBuffer.UV4Kind
  16035. * - BABYLON.VertexBuffer.UV5Kind
  16036. * - BABYLON.VertexBuffer.UV6Kind
  16037. * - BABYLON.VertexBuffer.ColorKind
  16038. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16039. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16040. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16041. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16042. *
  16043. * Returns the Mesh.
  16044. */
  16045. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16046. return this;
  16047. };
  16048. /**
  16049. * Sets the mesh indices.
  16050. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16051. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16052. * This method creates a new index buffer each call.
  16053. * Returns the Mesh.
  16054. */
  16055. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16056. return this;
  16057. };
  16058. /** Returns false by default, used by the class Mesh.
  16059. * Returns a boolean
  16060. */
  16061. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16062. return false;
  16063. };
  16064. /**
  16065. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16066. * Returns a BoundingInfo
  16067. */
  16068. AbstractMesh.prototype.getBoundingInfo = function () {
  16069. if (this._masterMesh) {
  16070. return this._masterMesh.getBoundingInfo();
  16071. }
  16072. if (!this._boundingInfo) {
  16073. // this._boundingInfo is being created here
  16074. this._updateBoundingInfo();
  16075. }
  16076. // cannot be null.
  16077. return this._boundingInfo;
  16078. };
  16079. /**
  16080. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16081. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16082. */
  16083. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16084. if (includeDescendants === void 0) { includeDescendants = true; }
  16085. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16086. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16087. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16088. if (maxDimension === 0) {
  16089. return this;
  16090. }
  16091. var scale = 1 / maxDimension;
  16092. this.scaling.scaleInPlace(scale);
  16093. return this;
  16094. };
  16095. /**
  16096. * Sets a mesh new object BoundingInfo.
  16097. * Returns the AbstractMesh.
  16098. */
  16099. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16100. this._boundingInfo = boundingInfo;
  16101. return this;
  16102. };
  16103. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16104. get: function () {
  16105. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16106. },
  16107. enumerable: true,
  16108. configurable: true
  16109. });
  16110. AbstractMesh.prototype._preActivate = function () {
  16111. };
  16112. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16113. };
  16114. AbstractMesh.prototype._activate = function (renderId) {
  16115. this._renderId = renderId;
  16116. };
  16117. /**
  16118. * Returns the latest update of the World matrix
  16119. * Returns a Matrix.
  16120. */
  16121. AbstractMesh.prototype.getWorldMatrix = function () {
  16122. if (this._masterMesh) {
  16123. return this._masterMesh.getWorldMatrix();
  16124. }
  16125. return _super.prototype.getWorldMatrix.call(this);
  16126. };
  16127. /**
  16128. * Returns the latest update of the World matrix determinant.
  16129. */
  16130. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16131. if (this._masterMesh) {
  16132. return this._masterMesh._getWorldMatrixDeterminant();
  16133. }
  16134. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16135. };
  16136. // ================================== Point of View Movement =================================
  16137. /**
  16138. * Perform relative position change from the point of view of behind the front of the mesh.
  16139. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16140. * Supports definition of mesh facing forward or backward.
  16141. * @param {number} amountRight
  16142. * @param {number} amountUp
  16143. * @param {number} amountForward
  16144. *
  16145. * Returns the AbstractMesh.
  16146. */
  16147. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16148. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16149. return this;
  16150. };
  16151. /**
  16152. * Calculate relative position change from the point of view of behind the front of the mesh.
  16153. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16154. * Supports definition of mesh facing forward or backward.
  16155. * @param {number} amountRight
  16156. * @param {number} amountUp
  16157. * @param {number} amountForward
  16158. *
  16159. * Returns a new Vector3.
  16160. */
  16161. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16162. var rotMatrix = new BABYLON.Matrix();
  16163. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16164. rotQuaternion.toRotationMatrix(rotMatrix);
  16165. var translationDelta = BABYLON.Vector3.Zero();
  16166. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16167. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16168. return translationDelta;
  16169. };
  16170. // ================================== Point of View Rotation =================================
  16171. /**
  16172. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16173. * Supports definition of mesh facing forward or backward.
  16174. * @param {number} flipBack
  16175. * @param {number} twirlClockwise
  16176. * @param {number} tiltRight
  16177. *
  16178. * Returns the AbstractMesh.
  16179. */
  16180. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16181. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16182. return this;
  16183. };
  16184. /**
  16185. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16186. * Supports definition of mesh facing forward or backward.
  16187. * @param {number} flipBack
  16188. * @param {number} twirlClockwise
  16189. * @param {number} tiltRight
  16190. *
  16191. * Returns a new Vector3.
  16192. */
  16193. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16194. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16195. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16196. };
  16197. /**
  16198. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16199. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16200. */
  16201. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16202. if (includeDescendants === void 0) { includeDescendants = true; }
  16203. this.computeWorldMatrix(true);
  16204. var min;
  16205. var max;
  16206. var boundingInfo = this.getBoundingInfo();
  16207. if (!this.subMeshes) {
  16208. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16209. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16210. }
  16211. else {
  16212. min = boundingInfo.boundingBox.minimumWorld;
  16213. max = boundingInfo.boundingBox.maximumWorld;
  16214. }
  16215. if (includeDescendants) {
  16216. var descendants = this.getDescendants(false);
  16217. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16218. var descendant = descendants_1[_i];
  16219. var childMesh = descendant;
  16220. childMesh.computeWorldMatrix(true);
  16221. //make sure we have the needed params to get mix and max
  16222. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16223. continue;
  16224. }
  16225. var childBoundingInfo = childMesh.getBoundingInfo();
  16226. var boundingBox = childBoundingInfo.boundingBox;
  16227. var minBox = boundingBox.minimumWorld;
  16228. var maxBox = boundingBox.maximumWorld;
  16229. BABYLON.Tools.CheckExtends(minBox, min, max);
  16230. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16231. }
  16232. }
  16233. return {
  16234. min: min,
  16235. max: max
  16236. };
  16237. };
  16238. /**
  16239. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16240. * Returns the AbstractMesh.
  16241. */
  16242. AbstractMesh.prototype._updateBoundingInfo = function () {
  16243. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16244. this._boundingInfo.update(this.worldMatrixFromCache);
  16245. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16246. return this;
  16247. };
  16248. /**
  16249. * Update a mesh's children BoundingInfo objects only.
  16250. * Returns the AbstractMesh.
  16251. */
  16252. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16253. if (!this.subMeshes) {
  16254. return this;
  16255. }
  16256. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16257. var subMesh = this.subMeshes[subIndex];
  16258. if (!subMesh.IsGlobal) {
  16259. subMesh.updateBoundingInfo(matrix);
  16260. }
  16261. }
  16262. return this;
  16263. };
  16264. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16265. // Bounding info
  16266. this._updateBoundingInfo();
  16267. };
  16268. /**
  16269. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16270. * A mesh is in the frustum if its bounding box intersects the frustum.
  16271. * Boolean returned.
  16272. */
  16273. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16274. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16275. };
  16276. /**
  16277. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16278. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16279. * Boolean returned.
  16280. */
  16281. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16282. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16283. ;
  16284. };
  16285. /**
  16286. * True if the mesh intersects another mesh or a SolidParticle object.
  16287. * 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)
  16288. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16289. * Returns a boolean.
  16290. */
  16291. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16292. if (precise === void 0) { precise = false; }
  16293. if (!this._boundingInfo || !mesh._boundingInfo) {
  16294. return false;
  16295. }
  16296. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16297. return true;
  16298. }
  16299. if (includeDescendants) {
  16300. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16301. var child = _a[_i];
  16302. if (child.intersectsMesh(mesh, precise, true)) {
  16303. return true;
  16304. }
  16305. }
  16306. }
  16307. return false;
  16308. };
  16309. /**
  16310. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16311. * Returns a boolean.
  16312. */
  16313. AbstractMesh.prototype.intersectsPoint = function (point) {
  16314. if (!this._boundingInfo) {
  16315. return false;
  16316. }
  16317. return this._boundingInfo.intersectsPoint(point);
  16318. };
  16319. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16320. return this.physicsImpostor;
  16321. };
  16322. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16323. if (camera === void 0) { camera = null; }
  16324. if (!camera) {
  16325. camera = this.getScene().activeCamera;
  16326. }
  16327. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16328. };
  16329. /**
  16330. * Returns the distance from the mesh to the active camera.
  16331. * Returns a float.
  16332. */
  16333. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16334. if (camera === void 0) { camera = null; }
  16335. if (!camera) {
  16336. camera = this.getScene().activeCamera;
  16337. }
  16338. return this.absolutePosition.subtract(camera.position).length();
  16339. };
  16340. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16341. if (!this.physicsImpostor) {
  16342. return this;
  16343. }
  16344. this.physicsImpostor.applyImpulse(force, contactPoint);
  16345. return this;
  16346. };
  16347. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16348. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16349. return this;
  16350. }
  16351. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16352. mainPivot: pivot1,
  16353. connectedPivot: pivot2,
  16354. nativeParams: options
  16355. });
  16356. return this;
  16357. };
  16358. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16359. // Collisions
  16360. /**
  16361. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16362. * Default `false`.
  16363. */
  16364. get: function () {
  16365. return this._checkCollisions;
  16366. },
  16367. set: function (collisionEnabled) {
  16368. this._checkCollisions = collisionEnabled;
  16369. if (this.getScene().workerCollisions) {
  16370. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16371. }
  16372. },
  16373. enumerable: true,
  16374. configurable: true
  16375. });
  16376. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16377. /**
  16378. * Gets Collider object used to compute collisions (not physics)
  16379. */
  16380. get: function () {
  16381. return this._collider;
  16382. },
  16383. enumerable: true,
  16384. configurable: true
  16385. });
  16386. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16387. var globalPosition = this.getAbsolutePosition();
  16388. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16389. if (!this._collider) {
  16390. this._collider = new BABYLON.Collider();
  16391. }
  16392. this._collider._radius = this.ellipsoid;
  16393. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16394. return this;
  16395. };
  16396. // Submeshes octree
  16397. /**
  16398. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16399. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16400. * Returns an Octree of submeshes.
  16401. */
  16402. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16403. if (maxCapacity === void 0) { maxCapacity = 64; }
  16404. if (maxDepth === void 0) { maxDepth = 2; }
  16405. if (!this._submeshesOctree) {
  16406. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16407. }
  16408. this.computeWorldMatrix(true);
  16409. var boundingInfo = this.getBoundingInfo();
  16410. // Update octree
  16411. var bbox = boundingInfo.boundingBox;
  16412. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16413. return this._submeshesOctree;
  16414. };
  16415. // Collisions
  16416. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16417. this._generatePointsArray();
  16418. if (!this._positions) {
  16419. return this;
  16420. }
  16421. // Transformation
  16422. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16423. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16424. subMesh._lastColliderWorldVertices = [];
  16425. subMesh._trianglePlanes = [];
  16426. var start = subMesh.verticesStart;
  16427. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16428. for (var i = start; i < end; i++) {
  16429. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16430. }
  16431. }
  16432. // Collide
  16433. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16434. if (collider.collisionFound) {
  16435. collider.collidedMesh = this;
  16436. }
  16437. return this;
  16438. };
  16439. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16440. var subMeshes;
  16441. var len;
  16442. // Octrees
  16443. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16444. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16445. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16446. len = intersections.length;
  16447. subMeshes = intersections.data;
  16448. }
  16449. else {
  16450. subMeshes = this.subMeshes;
  16451. len = subMeshes.length;
  16452. }
  16453. for (var index = 0; index < len; index++) {
  16454. var subMesh = subMeshes[index];
  16455. // Bounding test
  16456. if (len > 1 && !subMesh._checkCollision(collider))
  16457. continue;
  16458. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16459. }
  16460. return this;
  16461. };
  16462. AbstractMesh.prototype._checkCollision = function (collider) {
  16463. // Bounding box test
  16464. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16465. return this;
  16466. // Transformation matrix
  16467. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16468. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16469. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16470. return this;
  16471. };
  16472. // Picking
  16473. AbstractMesh.prototype._generatePointsArray = function () {
  16474. return false;
  16475. };
  16476. /**
  16477. * Checks if the passed Ray intersects with the mesh.
  16478. * Returns an object PickingInfo.
  16479. */
  16480. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16481. var pickingInfo = new BABYLON.PickingInfo();
  16482. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16483. return pickingInfo;
  16484. }
  16485. if (!this._generatePointsArray()) {
  16486. return pickingInfo;
  16487. }
  16488. var intersectInfo = null;
  16489. // Octrees
  16490. var subMeshes;
  16491. var len;
  16492. if (this._submeshesOctree && this.useOctreeForPicking) {
  16493. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16494. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16495. len = intersections.length;
  16496. subMeshes = intersections.data;
  16497. }
  16498. else {
  16499. subMeshes = this.subMeshes;
  16500. len = subMeshes.length;
  16501. }
  16502. for (var index = 0; index < len; index++) {
  16503. var subMesh = subMeshes[index];
  16504. // Bounding test
  16505. if (len > 1 && !subMesh.canIntersects(ray))
  16506. continue;
  16507. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16508. if (currentIntersectInfo) {
  16509. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16510. intersectInfo = currentIntersectInfo;
  16511. intersectInfo.subMeshId = index;
  16512. if (fastCheck) {
  16513. break;
  16514. }
  16515. }
  16516. }
  16517. }
  16518. if (intersectInfo) {
  16519. // Get picked point
  16520. var world = this.getWorldMatrix();
  16521. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16522. var direction = ray.direction.clone();
  16523. direction = direction.scale(intersectInfo.distance);
  16524. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16525. var pickedPoint = worldOrigin.add(worldDirection);
  16526. // Return result
  16527. pickingInfo.hit = true;
  16528. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16529. pickingInfo.pickedPoint = pickedPoint;
  16530. pickingInfo.pickedMesh = this;
  16531. pickingInfo.bu = intersectInfo.bu || 0;
  16532. pickingInfo.bv = intersectInfo.bv || 0;
  16533. pickingInfo.faceId = intersectInfo.faceId;
  16534. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16535. return pickingInfo;
  16536. }
  16537. return pickingInfo;
  16538. };
  16539. /**
  16540. * Clones the mesh, used by the class Mesh.
  16541. * Just returns `null` for an AbstractMesh.
  16542. */
  16543. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16544. return null;
  16545. };
  16546. /**
  16547. * Disposes all the mesh submeshes.
  16548. * Returns the AbstractMesh.
  16549. */
  16550. AbstractMesh.prototype.releaseSubMeshes = function () {
  16551. if (this.subMeshes) {
  16552. while (this.subMeshes.length) {
  16553. this.subMeshes[0].dispose();
  16554. }
  16555. }
  16556. else {
  16557. this.subMeshes = new Array();
  16558. }
  16559. return this;
  16560. };
  16561. /**
  16562. * Disposes the AbstractMesh.
  16563. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16564. * Returns nothing.
  16565. */
  16566. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16567. var _this = this;
  16568. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16569. var index;
  16570. // Action manager
  16571. if (this.actionManager !== undefined && this.actionManager !== null) {
  16572. this.actionManager.dispose();
  16573. this.actionManager = null;
  16574. }
  16575. // Skeleton
  16576. this.skeleton = null;
  16577. // Physics
  16578. if (this.physicsImpostor) {
  16579. this.physicsImpostor.dispose();
  16580. }
  16581. // Intersections in progress
  16582. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16583. var other = this._intersectionsInProgress[index];
  16584. var pos = other._intersectionsInProgress.indexOf(this);
  16585. other._intersectionsInProgress.splice(pos, 1);
  16586. }
  16587. this._intersectionsInProgress = [];
  16588. // Lights
  16589. var lights = this.getScene().lights;
  16590. lights.forEach(function (light) {
  16591. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16592. if (meshIndex !== -1) {
  16593. light.includedOnlyMeshes.splice(meshIndex, 1);
  16594. }
  16595. meshIndex = light.excludedMeshes.indexOf(_this);
  16596. if (meshIndex !== -1) {
  16597. light.excludedMeshes.splice(meshIndex, 1);
  16598. }
  16599. // Shadow generators
  16600. var generator = light.getShadowGenerator();
  16601. if (generator) {
  16602. var shadowMap = generator.getShadowMap();
  16603. if (shadowMap && shadowMap.renderList) {
  16604. meshIndex = shadowMap.renderList.indexOf(_this);
  16605. if (meshIndex !== -1) {
  16606. shadowMap.renderList.splice(meshIndex, 1);
  16607. }
  16608. }
  16609. }
  16610. });
  16611. // Edges
  16612. if (this._edgesRenderer) {
  16613. this._edgesRenderer.dispose();
  16614. this._edgesRenderer = null;
  16615. }
  16616. // SubMeshes
  16617. if (this.getClassName() !== "InstancedMesh") {
  16618. this.releaseSubMeshes();
  16619. }
  16620. // Octree
  16621. var sceneOctree = this.getScene().selectionOctree;
  16622. if (sceneOctree !== undefined && sceneOctree !== null) {
  16623. var index = sceneOctree.dynamicContent.indexOf(this);
  16624. if (index !== -1) {
  16625. sceneOctree.dynamicContent.splice(index, 1);
  16626. }
  16627. }
  16628. // Query
  16629. var engine = this.getScene().getEngine();
  16630. if (this._occlusionQuery) {
  16631. this._isOcclusionQueryInProgress = false;
  16632. engine.deleteQuery(this._occlusionQuery);
  16633. this._occlusionQuery = null;
  16634. }
  16635. // Engine
  16636. engine.wipeCaches();
  16637. // Remove from scene
  16638. this.getScene().removeMesh(this);
  16639. if (disposeMaterialAndTextures) {
  16640. if (this.material) {
  16641. this.material.dispose(false, true);
  16642. }
  16643. }
  16644. if (!doNotRecurse) {
  16645. // Particles
  16646. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16647. if (this.getScene().particleSystems[index].emitter === this) {
  16648. this.getScene().particleSystems[index].dispose();
  16649. index--;
  16650. }
  16651. }
  16652. }
  16653. // facet data
  16654. if (this._facetDataEnabled) {
  16655. this.disableFacetData();
  16656. }
  16657. this.onAfterWorldMatrixUpdateObservable.clear();
  16658. this.onCollideObservable.clear();
  16659. this.onCollisionPositionChangeObservable.clear();
  16660. this._isDisposed = true;
  16661. _super.prototype.dispose.call(this, doNotRecurse);
  16662. };
  16663. /**
  16664. * Adds the passed mesh as a child to the current mesh.
  16665. * Returns the AbstractMesh.
  16666. */
  16667. AbstractMesh.prototype.addChild = function (mesh) {
  16668. mesh.setParent(this);
  16669. return this;
  16670. };
  16671. /**
  16672. * Removes the passed mesh from the current mesh children list.
  16673. * Returns the AbstractMesh.
  16674. */
  16675. AbstractMesh.prototype.removeChild = function (mesh) {
  16676. mesh.setParent(null);
  16677. return this;
  16678. };
  16679. // Facet data
  16680. /**
  16681. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16682. * Returns the AbstractMesh.
  16683. */
  16684. AbstractMesh.prototype._initFacetData = function () {
  16685. if (!this._facetNormals) {
  16686. this._facetNormals = new Array();
  16687. }
  16688. if (!this._facetPositions) {
  16689. this._facetPositions = new Array();
  16690. }
  16691. if (!this._facetPartitioning) {
  16692. this._facetPartitioning = new Array();
  16693. }
  16694. this._facetNb = (this.getIndices().length / 3) | 0;
  16695. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16696. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16697. for (var f = 0; f < this._facetNb; f++) {
  16698. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16699. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16700. }
  16701. this._facetDataEnabled = true;
  16702. return this;
  16703. };
  16704. /**
  16705. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16706. * This method can be called within the render loop.
  16707. * 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.
  16708. * Returns the AbstractMesh.
  16709. */
  16710. AbstractMesh.prototype.updateFacetData = function () {
  16711. if (!this._facetDataEnabled) {
  16712. this._initFacetData();
  16713. }
  16714. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16715. var indices = this.getIndices();
  16716. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16717. var bInfo = this.getBoundingInfo();
  16718. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16719. // init arrays, matrix and sort function on first call
  16720. this._facetDepthSortEnabled = true;
  16721. if (indices instanceof Uint16Array) {
  16722. this._depthSortedIndices = new Uint16Array(indices);
  16723. }
  16724. else if (indices instanceof Uint32Array) {
  16725. this._depthSortedIndices = new Uint32Array(indices);
  16726. }
  16727. else {
  16728. var needs32bits = false;
  16729. for (var i = 0; i < indices.length; i++) {
  16730. if (indices[i] > 65535) {
  16731. needs32bits = true;
  16732. break;
  16733. }
  16734. }
  16735. if (needs32bits) {
  16736. this._depthSortedIndices = new Uint32Array(indices);
  16737. }
  16738. else {
  16739. this._depthSortedIndices = new Uint16Array(indices);
  16740. }
  16741. }
  16742. this._facetDepthSortFunction = function (f1, f2) {
  16743. return (f2.sqDistance - f1.sqDistance);
  16744. };
  16745. if (!this._facetDepthSortFrom) {
  16746. var camera = this.getScene().activeCamera;
  16747. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16748. }
  16749. this._depthSortedFacets = [];
  16750. for (var f = 0; f < this._facetNb; f++) {
  16751. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16752. this._depthSortedFacets.push(depthSortedFacet);
  16753. }
  16754. this._invertedMatrix = BABYLON.Matrix.Identity();
  16755. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16756. }
  16757. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16758. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16759. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16760. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16761. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16762. this._subDiv.max = this._partitioningSubdivisions;
  16763. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16764. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16765. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16766. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16767. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16768. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16769. // set the parameters for ComputeNormals()
  16770. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16771. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16772. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16773. this._facetParameters.bInfo = bInfo;
  16774. this._facetParameters.bbSize = this._bbSize;
  16775. this._facetParameters.subDiv = this._subDiv;
  16776. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16777. this._facetParameters.depthSort = this._facetDepthSort;
  16778. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16779. this.computeWorldMatrix(true);
  16780. this._worldMatrix.invertToRef(this._invertedMatrix);
  16781. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16782. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16783. }
  16784. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16785. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16786. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16787. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16788. var l = (this._depthSortedIndices.length / 3) | 0;
  16789. for (var f = 0; f < l; f++) {
  16790. var sind = this._depthSortedFacets[f].ind;
  16791. this._depthSortedIndices[f * 3] = indices[sind];
  16792. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16793. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16794. }
  16795. this.updateIndices(this._depthSortedIndices);
  16796. }
  16797. return this;
  16798. };
  16799. /**
  16800. * Returns the facetLocalNormals array.
  16801. * The normals are expressed in the mesh local space.
  16802. */
  16803. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16804. if (!this._facetNormals) {
  16805. this.updateFacetData();
  16806. }
  16807. return this._facetNormals;
  16808. };
  16809. /**
  16810. * Returns the facetLocalPositions array.
  16811. * The facet positions are expressed in the mesh local space.
  16812. */
  16813. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16814. if (!this._facetPositions) {
  16815. this.updateFacetData();
  16816. }
  16817. return this._facetPositions;
  16818. };
  16819. /**
  16820. * Returns the facetLocalPartioning array.
  16821. */
  16822. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16823. if (!this._facetPartitioning) {
  16824. this.updateFacetData();
  16825. }
  16826. return this._facetPartitioning;
  16827. };
  16828. /**
  16829. * Returns the i-th facet position in the world system.
  16830. * This method allocates a new Vector3 per call.
  16831. */
  16832. AbstractMesh.prototype.getFacetPosition = function (i) {
  16833. var pos = BABYLON.Vector3.Zero();
  16834. this.getFacetPositionToRef(i, pos);
  16835. return pos;
  16836. };
  16837. /**
  16838. * Sets the reference Vector3 with the i-th facet position in the world system.
  16839. * Returns the AbstractMesh.
  16840. */
  16841. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16842. var localPos = (this.getFacetLocalPositions())[i];
  16843. var world = this.getWorldMatrix();
  16844. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16845. return this;
  16846. };
  16847. /**
  16848. * Returns the i-th facet normal in the world system.
  16849. * This method allocates a new Vector3 per call.
  16850. */
  16851. AbstractMesh.prototype.getFacetNormal = function (i) {
  16852. var norm = BABYLON.Vector3.Zero();
  16853. this.getFacetNormalToRef(i, norm);
  16854. return norm;
  16855. };
  16856. /**
  16857. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16858. * Returns the AbstractMesh.
  16859. */
  16860. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16861. var localNorm = (this.getFacetLocalNormals())[i];
  16862. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16863. return this;
  16864. };
  16865. /**
  16866. * 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).
  16867. */
  16868. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16869. var bInfo = this.getBoundingInfo();
  16870. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16871. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16872. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16873. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16874. return null;
  16875. }
  16876. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16877. };
  16878. /**
  16879. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16880. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16881. * 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.
  16882. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16883. * 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.
  16884. */
  16885. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16886. if (checkFace === void 0) { checkFace = false; }
  16887. if (facing === void 0) { facing = true; }
  16888. var world = this.getWorldMatrix();
  16889. var invMat = BABYLON.Tmp.Matrix[5];
  16890. world.invertToRef(invMat);
  16891. var invVect = BABYLON.Tmp.Vector3[8];
  16892. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16893. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16894. if (projected) {
  16895. // tranform the local computed projected vector to world coordinates
  16896. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16897. }
  16898. return closest;
  16899. };
  16900. /**
  16901. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16902. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16903. * 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.
  16904. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16905. * 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.
  16906. */
  16907. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16908. if (checkFace === void 0) { checkFace = false; }
  16909. if (facing === void 0) { facing = true; }
  16910. var closest = null;
  16911. var tmpx = 0.0;
  16912. var tmpy = 0.0;
  16913. var tmpz = 0.0;
  16914. var d = 0.0; // tmp dot facet normal * facet position
  16915. var t0 = 0.0;
  16916. var projx = 0.0;
  16917. var projy = 0.0;
  16918. var projz = 0.0;
  16919. // Get all the facets in the same partitioning block than (x, y, z)
  16920. var facetPositions = this.getFacetLocalPositions();
  16921. var facetNormals = this.getFacetLocalNormals();
  16922. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16923. if (!facetsInBlock) {
  16924. return null;
  16925. }
  16926. // Get the closest facet to (x, y, z)
  16927. var shortest = Number.MAX_VALUE; // init distance vars
  16928. var tmpDistance = shortest;
  16929. var fib; // current facet in the block
  16930. var norm; // current facet normal
  16931. var p0; // current facet barycenter position
  16932. // loop on all the facets in the current partitioning block
  16933. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16934. fib = facetsInBlock[idx];
  16935. norm = facetNormals[fib];
  16936. p0 = facetPositions[fib];
  16937. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16938. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16939. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16940. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16941. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16942. projx = x + norm.x * t0;
  16943. projy = y + norm.y * t0;
  16944. projz = z + norm.z * t0;
  16945. tmpx = projx - x;
  16946. tmpy = projy - y;
  16947. tmpz = projz - z;
  16948. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16949. if (tmpDistance < shortest) {
  16950. shortest = tmpDistance;
  16951. closest = fib;
  16952. if (projected) {
  16953. projected.x = projx;
  16954. projected.y = projy;
  16955. projected.z = projz;
  16956. }
  16957. }
  16958. }
  16959. }
  16960. return closest;
  16961. };
  16962. /**
  16963. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16964. */
  16965. AbstractMesh.prototype.getFacetDataParameters = function () {
  16966. return this._facetParameters;
  16967. };
  16968. /**
  16969. * Disables the feature FacetData and frees the related memory.
  16970. * Returns the AbstractMesh.
  16971. */
  16972. AbstractMesh.prototype.disableFacetData = function () {
  16973. if (this._facetDataEnabled) {
  16974. this._facetDataEnabled = false;
  16975. this._facetPositions = new Array();
  16976. this._facetNormals = new Array();
  16977. this._facetPartitioning = new Array();
  16978. this._facetParameters = null;
  16979. this._depthSortedIndices = new Uint32Array(0);
  16980. }
  16981. return this;
  16982. };
  16983. /**
  16984. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16985. * Returns the mesh.
  16986. */
  16987. AbstractMesh.prototype.updateIndices = function (indices) {
  16988. return this;
  16989. };
  16990. /**
  16991. * The mesh Geometry. Actually used by the Mesh object.
  16992. * Returns a blank geometry object.
  16993. */
  16994. /**
  16995. * Creates new normals data for the mesh.
  16996. * @param updatable.
  16997. */
  16998. AbstractMesh.prototype.createNormals = function (updatable) {
  16999. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17000. var indices = this.getIndices();
  17001. var normals;
  17002. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17003. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17004. }
  17005. else {
  17006. normals = [];
  17007. }
  17008. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17009. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17010. };
  17011. /**
  17012. * Align the mesh with a normal.
  17013. * Returns the mesh.
  17014. */
  17015. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17016. if (!upDirection) {
  17017. upDirection = BABYLON.Axis.Y;
  17018. }
  17019. var axisX = BABYLON.Tmp.Vector3[0];
  17020. var axisZ = BABYLON.Tmp.Vector3[1];
  17021. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17022. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17023. if (this.rotationQuaternion) {
  17024. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17025. }
  17026. else {
  17027. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17028. }
  17029. return this;
  17030. };
  17031. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17032. var engine = this.getEngine();
  17033. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17034. this._isOccluded = false;
  17035. return;
  17036. }
  17037. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17038. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17039. if (isOcclusionQueryAvailable) {
  17040. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17041. this._isOcclusionQueryInProgress = false;
  17042. this._occlusionInternalRetryCounter = 0;
  17043. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17044. }
  17045. else {
  17046. this._occlusionInternalRetryCounter++;
  17047. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17048. this._isOcclusionQueryInProgress = false;
  17049. this._occlusionInternalRetryCounter = 0;
  17050. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17051. // if strict continue the last state of the object.
  17052. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17053. }
  17054. else {
  17055. return;
  17056. }
  17057. }
  17058. }
  17059. var scene = this.getScene();
  17060. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17061. if (!this._occlusionQuery) {
  17062. this._occlusionQuery = engine.createQuery();
  17063. }
  17064. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17065. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17066. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17067. this._isOcclusionQueryInProgress = true;
  17068. };
  17069. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17070. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17071. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17072. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17073. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17074. return AbstractMesh;
  17075. }(BABYLON.TransformNode));
  17076. BABYLON.AbstractMesh = AbstractMesh;
  17077. })(BABYLON || (BABYLON = {}));
  17078. //# sourceMappingURL=babylon.abstractMesh.js.map
  17079. var BABYLON;
  17080. (function (BABYLON) {
  17081. var Light = /** @class */ (function (_super) {
  17082. __extends(Light, _super);
  17083. /**
  17084. * Creates a Light object in the scene.
  17085. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17086. */
  17087. function Light(name, scene) {
  17088. var _this = _super.call(this, name, scene) || this;
  17089. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17090. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17091. _this.intensity = 1.0;
  17092. _this.range = Number.MAX_VALUE;
  17093. /**
  17094. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17095. * of light.
  17096. */
  17097. _this._photometricScale = 1.0;
  17098. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17099. _this._radius = 0.00001;
  17100. _this.renderPriority = 0;
  17101. /**
  17102. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17103. * the current shadow generator.
  17104. */
  17105. _this.shadowEnabled = true;
  17106. _this._excludeWithLayerMask = 0;
  17107. _this._includeOnlyWithLayerMask = 0;
  17108. _this._lightmapMode = 0;
  17109. _this._excludedMeshesIds = new Array();
  17110. _this._includedOnlyMeshesIds = new Array();
  17111. _this.getScene().addLight(_this);
  17112. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17113. _this._buildUniformLayout();
  17114. _this.includedOnlyMeshes = new Array();
  17115. _this.excludedMeshes = new Array();
  17116. _this._resyncMeshes();
  17117. return _this;
  17118. }
  17119. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17120. /**
  17121. * If every light affecting the material is in this lightmapMode,
  17122. * material.lightmapTexture adds or multiplies
  17123. * (depends on material.useLightmapAsShadowmap)
  17124. * after every other light calculations.
  17125. */
  17126. get: function () {
  17127. return Light._LIGHTMAP_DEFAULT;
  17128. },
  17129. enumerable: true,
  17130. configurable: true
  17131. });
  17132. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17133. /**
  17134. * material.lightmapTexture as only diffuse lighting from this light
  17135. * adds only specular lighting from this light
  17136. * adds dynamic shadows
  17137. */
  17138. get: function () {
  17139. return Light._LIGHTMAP_SPECULAR;
  17140. },
  17141. enumerable: true,
  17142. configurable: true
  17143. });
  17144. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17145. /**
  17146. * material.lightmapTexture as only lighting
  17147. * no light calculation from this light
  17148. * only adds dynamic shadows from this light
  17149. */
  17150. get: function () {
  17151. return Light._LIGHTMAP_SHADOWSONLY;
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17157. /**
  17158. * Each light type uses the default quantity according to its type:
  17159. * point/spot lights use luminous intensity
  17160. * directional lights use illuminance
  17161. */
  17162. get: function () {
  17163. return Light._INTENSITYMODE_AUTOMATIC;
  17164. },
  17165. enumerable: true,
  17166. configurable: true
  17167. });
  17168. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17169. /**
  17170. * lumen (lm)
  17171. */
  17172. get: function () {
  17173. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17174. },
  17175. enumerable: true,
  17176. configurable: true
  17177. });
  17178. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17179. /**
  17180. * candela (lm/sr)
  17181. */
  17182. get: function () {
  17183. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17184. },
  17185. enumerable: true,
  17186. configurable: true
  17187. });
  17188. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17189. /**
  17190. * lux (lm/m^2)
  17191. */
  17192. get: function () {
  17193. return Light._INTENSITYMODE_ILLUMINANCE;
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17199. /**
  17200. * nit (cd/m^2)
  17201. */
  17202. get: function () {
  17203. return Light._INTENSITYMODE_LUMINANCE;
  17204. },
  17205. enumerable: true,
  17206. configurable: true
  17207. });
  17208. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17209. /**
  17210. * Light type const id of the point light.
  17211. */
  17212. get: function () {
  17213. return Light._LIGHTTYPEID_POINTLIGHT;
  17214. },
  17215. enumerable: true,
  17216. configurable: true
  17217. });
  17218. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17219. /**
  17220. * Light type const id of the directional light.
  17221. */
  17222. get: function () {
  17223. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17224. },
  17225. enumerable: true,
  17226. configurable: true
  17227. });
  17228. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17229. /**
  17230. * Light type const id of the spot light.
  17231. */
  17232. get: function () {
  17233. return Light._LIGHTTYPEID_SPOTLIGHT;
  17234. },
  17235. enumerable: true,
  17236. configurable: true
  17237. });
  17238. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17239. /**
  17240. * Light type const id of the hemispheric light.
  17241. */
  17242. get: function () {
  17243. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(Light.prototype, "intensityMode", {
  17249. /**
  17250. * Gets the photometric scale used to interpret the intensity.
  17251. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17252. */
  17253. get: function () {
  17254. return this._intensityMode;
  17255. },
  17256. /**
  17257. * Sets the photometric scale used to interpret the intensity.
  17258. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17259. */
  17260. set: function (value) {
  17261. this._intensityMode = value;
  17262. this._computePhotometricScale();
  17263. },
  17264. enumerable: true,
  17265. configurable: true
  17266. });
  17267. ;
  17268. ;
  17269. Object.defineProperty(Light.prototype, "radius", {
  17270. /**
  17271. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17272. */
  17273. get: function () {
  17274. return this._radius;
  17275. },
  17276. /**
  17277. * sets the light radius used by PBR Materials to simulate soft area lights.
  17278. */
  17279. set: function (value) {
  17280. this._radius = value;
  17281. this._computePhotometricScale();
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. ;
  17287. ;
  17288. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17289. get: function () {
  17290. return this._includedOnlyMeshes;
  17291. },
  17292. set: function (value) {
  17293. this._includedOnlyMeshes = value;
  17294. this._hookArrayForIncludedOnly(value);
  17295. },
  17296. enumerable: true,
  17297. configurable: true
  17298. });
  17299. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17300. get: function () {
  17301. return this._excludedMeshes;
  17302. },
  17303. set: function (value) {
  17304. this._excludedMeshes = value;
  17305. this._hookArrayForExcluded(value);
  17306. },
  17307. enumerable: true,
  17308. configurable: true
  17309. });
  17310. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17311. get: function () {
  17312. return this._excludeWithLayerMask;
  17313. },
  17314. set: function (value) {
  17315. this._excludeWithLayerMask = value;
  17316. this._resyncMeshes();
  17317. },
  17318. enumerable: true,
  17319. configurable: true
  17320. });
  17321. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17322. get: function () {
  17323. return this._includeOnlyWithLayerMask;
  17324. },
  17325. set: function (value) {
  17326. this._includeOnlyWithLayerMask = value;
  17327. this._resyncMeshes();
  17328. },
  17329. enumerable: true,
  17330. configurable: true
  17331. });
  17332. Object.defineProperty(Light.prototype, "lightmapMode", {
  17333. get: function () {
  17334. return this._lightmapMode;
  17335. },
  17336. set: function (value) {
  17337. if (this._lightmapMode === value) {
  17338. return;
  17339. }
  17340. this._lightmapMode = value;
  17341. this._markMeshesAsLightDirty();
  17342. },
  17343. enumerable: true,
  17344. configurable: true
  17345. });
  17346. Light.prototype._buildUniformLayout = function () {
  17347. // Overridden
  17348. };
  17349. /**
  17350. * Returns the string "Light".
  17351. */
  17352. Light.prototype.getClassName = function () {
  17353. return "Light";
  17354. };
  17355. /**
  17356. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17357. */
  17358. Light.prototype.toString = function (fullDetails) {
  17359. var ret = "Name: " + this.name;
  17360. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17361. if (this.animations) {
  17362. for (var i = 0; i < this.animations.length; i++) {
  17363. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17364. }
  17365. }
  17366. if (fullDetails) {
  17367. }
  17368. return ret;
  17369. };
  17370. /**
  17371. * Set the enabled state of this node.
  17372. * @param {boolean} value - the new enabled state
  17373. * @see isEnabled
  17374. */
  17375. Light.prototype.setEnabled = function (value) {
  17376. _super.prototype.setEnabled.call(this, value);
  17377. this._resyncMeshes();
  17378. };
  17379. /**
  17380. * Returns the Light associated shadow generator.
  17381. */
  17382. Light.prototype.getShadowGenerator = function () {
  17383. return this._shadowGenerator;
  17384. };
  17385. /**
  17386. * Returns a Vector3, the absolute light position in the World.
  17387. */
  17388. Light.prototype.getAbsolutePosition = function () {
  17389. return BABYLON.Vector3.Zero();
  17390. };
  17391. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17392. };
  17393. Light.prototype._getWorldMatrix = function () {
  17394. return BABYLON.Matrix.Identity();
  17395. };
  17396. /**
  17397. * Boolean : True if the light will affect the passed mesh.
  17398. */
  17399. Light.prototype.canAffectMesh = function (mesh) {
  17400. if (!mesh) {
  17401. return true;
  17402. }
  17403. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17404. return false;
  17405. }
  17406. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17407. return false;
  17408. }
  17409. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17410. return false;
  17411. }
  17412. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17413. return false;
  17414. }
  17415. return true;
  17416. };
  17417. /**
  17418. * Returns the light World matrix.
  17419. */
  17420. Light.prototype.getWorldMatrix = function () {
  17421. this._currentRenderId = this.getScene().getRenderId();
  17422. var worldMatrix = this._getWorldMatrix();
  17423. if (this.parent && this.parent.getWorldMatrix) {
  17424. if (!this._parentedWorldMatrix) {
  17425. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17426. }
  17427. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17428. this._markSyncedWithParent();
  17429. return this._parentedWorldMatrix;
  17430. }
  17431. return worldMatrix;
  17432. };
  17433. /**
  17434. * Sort function to order lights for rendering.
  17435. * @param a First Light object to compare to second.
  17436. * @param b Second Light object to compare first.
  17437. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17438. */
  17439. Light.compareLightsPriority = function (a, b) {
  17440. //shadow-casting lights have priority over non-shadow-casting lights
  17441. //the renderPrioirty is a secondary sort criterion
  17442. if (a.shadowEnabled !== b.shadowEnabled) {
  17443. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17444. }
  17445. return b.renderPriority - a.renderPriority;
  17446. };
  17447. /**
  17448. * Disposes the light.
  17449. */
  17450. Light.prototype.dispose = function () {
  17451. if (this._shadowGenerator) {
  17452. this._shadowGenerator.dispose();
  17453. this._shadowGenerator = null;
  17454. }
  17455. // Animations
  17456. this.getScene().stopAnimation(this);
  17457. this._uniformBuffer.dispose();
  17458. // Remove from scene
  17459. this.getScene().removeLight(this);
  17460. _super.prototype.dispose.call(this);
  17461. };
  17462. /**
  17463. * Returns the light type ID (integer).
  17464. */
  17465. Light.prototype.getTypeID = function () {
  17466. return 0;
  17467. };
  17468. /**
  17469. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17470. */
  17471. Light.prototype.getScaledIntensity = function () {
  17472. return this._photometricScale * this.intensity;
  17473. };
  17474. /**
  17475. * Returns a new Light object, named "name", from the current one.
  17476. */
  17477. Light.prototype.clone = function (name) {
  17478. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17479. if (!constructor) {
  17480. return null;
  17481. }
  17482. return BABYLON.SerializationHelper.Clone(constructor, this);
  17483. };
  17484. /**
  17485. * Serializes the current light into a Serialization object.
  17486. * Returns the serialized object.
  17487. */
  17488. Light.prototype.serialize = function () {
  17489. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17490. // Type
  17491. serializationObject.type = this.getTypeID();
  17492. // Parent
  17493. if (this.parent) {
  17494. serializationObject.parentId = this.parent.id;
  17495. }
  17496. // Inclusion / exclusions
  17497. if (this.excludedMeshes.length > 0) {
  17498. serializationObject.excludedMeshesIds = [];
  17499. this.excludedMeshes.forEach(function (mesh) {
  17500. serializationObject.excludedMeshesIds.push(mesh.id);
  17501. });
  17502. }
  17503. if (this.includedOnlyMeshes.length > 0) {
  17504. serializationObject.includedOnlyMeshesIds = [];
  17505. this.includedOnlyMeshes.forEach(function (mesh) {
  17506. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17507. });
  17508. }
  17509. // Animations
  17510. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17511. serializationObject.ranges = this.serializeAnimationRanges();
  17512. return serializationObject;
  17513. };
  17514. /**
  17515. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17516. * This new light is named "name" and added to the passed scene.
  17517. */
  17518. Light.GetConstructorFromName = function (type, name, scene) {
  17519. switch (type) {
  17520. case 0:
  17521. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17522. case 1:
  17523. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17524. case 2:
  17525. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17526. case 3:
  17527. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17528. }
  17529. return null;
  17530. };
  17531. /**
  17532. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17533. */
  17534. Light.Parse = function (parsedLight, scene) {
  17535. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17536. if (!constructor) {
  17537. return null;
  17538. }
  17539. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17540. // Inclusion / exclusions
  17541. if (parsedLight.excludedMeshesIds) {
  17542. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17543. }
  17544. if (parsedLight.includedOnlyMeshesIds) {
  17545. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17546. }
  17547. // Parent
  17548. if (parsedLight.parentId) {
  17549. light._waitingParentId = parsedLight.parentId;
  17550. }
  17551. // Animations
  17552. if (parsedLight.animations) {
  17553. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17554. var parsedAnimation = parsedLight.animations[animationIndex];
  17555. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17556. }
  17557. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17558. }
  17559. if (parsedLight.autoAnimate) {
  17560. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17561. }
  17562. return light;
  17563. };
  17564. Light.prototype._hookArrayForExcluded = function (array) {
  17565. var _this = this;
  17566. var oldPush = array.push;
  17567. array.push = function () {
  17568. var items = [];
  17569. for (var _i = 0; _i < arguments.length; _i++) {
  17570. items[_i] = arguments[_i];
  17571. }
  17572. var result = oldPush.apply(array, items);
  17573. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17574. var item = items_1[_a];
  17575. item._resyncLighSource(_this);
  17576. }
  17577. return result;
  17578. };
  17579. var oldSplice = array.splice;
  17580. array.splice = function (index, deleteCount) {
  17581. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17582. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17583. var item = deleted_1[_i];
  17584. item._resyncLighSource(_this);
  17585. }
  17586. return deleted;
  17587. };
  17588. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17589. var item = array_1[_i];
  17590. item._resyncLighSource(this);
  17591. }
  17592. };
  17593. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17594. var _this = this;
  17595. var oldPush = array.push;
  17596. array.push = function () {
  17597. var items = [];
  17598. for (var _i = 0; _i < arguments.length; _i++) {
  17599. items[_i] = arguments[_i];
  17600. }
  17601. var result = oldPush.apply(array, items);
  17602. _this._resyncMeshes();
  17603. return result;
  17604. };
  17605. var oldSplice = array.splice;
  17606. array.splice = function (index, deleteCount) {
  17607. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17608. _this._resyncMeshes();
  17609. return deleted;
  17610. };
  17611. this._resyncMeshes();
  17612. };
  17613. Light.prototype._resyncMeshes = function () {
  17614. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17615. var mesh = _a[_i];
  17616. mesh._resyncLighSource(this);
  17617. }
  17618. };
  17619. Light.prototype._markMeshesAsLightDirty = function () {
  17620. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17621. var mesh = _a[_i];
  17622. if (mesh._lightSources.indexOf(this) !== -1) {
  17623. mesh._markSubMeshesAsLightDirty();
  17624. }
  17625. }
  17626. };
  17627. /**
  17628. * Recomputes the cached photometric scale if needed.
  17629. */
  17630. Light.prototype._computePhotometricScale = function () {
  17631. this._photometricScale = this._getPhotometricScale();
  17632. this.getScene().resetCachedMaterial();
  17633. };
  17634. /**
  17635. * Returns the Photometric Scale according to the light type and intensity mode.
  17636. */
  17637. Light.prototype._getPhotometricScale = function () {
  17638. var photometricScale = 0.0;
  17639. var lightTypeID = this.getTypeID();
  17640. //get photometric mode
  17641. var photometricMode = this.intensityMode;
  17642. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17643. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17644. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17645. }
  17646. else {
  17647. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17648. }
  17649. }
  17650. //compute photometric scale
  17651. switch (lightTypeID) {
  17652. case Light.LIGHTTYPEID_POINTLIGHT:
  17653. case Light.LIGHTTYPEID_SPOTLIGHT:
  17654. switch (photometricMode) {
  17655. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17656. photometricScale = 1.0 / (4.0 * Math.PI);
  17657. break;
  17658. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17659. photometricScale = 1.0;
  17660. break;
  17661. case Light.INTENSITYMODE_LUMINANCE:
  17662. photometricScale = this.radius * this.radius;
  17663. break;
  17664. }
  17665. break;
  17666. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17667. switch (photometricMode) {
  17668. case Light.INTENSITYMODE_ILLUMINANCE:
  17669. photometricScale = 1.0;
  17670. break;
  17671. case Light.INTENSITYMODE_LUMINANCE:
  17672. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17673. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17674. var apexAngleRadians = this.radius;
  17675. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17676. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17677. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17678. photometricScale = solidAngle;
  17679. break;
  17680. }
  17681. break;
  17682. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17683. // No fall off in hemisperic light.
  17684. photometricScale = 1.0;
  17685. break;
  17686. }
  17687. return photometricScale;
  17688. };
  17689. Light.prototype._reorderLightsInScene = function () {
  17690. var scene = this.getScene();
  17691. if (this._renderPriority != 0) {
  17692. scene.requireLightSorting = true;
  17693. }
  17694. this.getScene().sortLightsByPriority();
  17695. };
  17696. //lightmapMode Consts
  17697. Light._LIGHTMAP_DEFAULT = 0;
  17698. Light._LIGHTMAP_SPECULAR = 1;
  17699. Light._LIGHTMAP_SHADOWSONLY = 2;
  17700. // Intensity Mode Consts
  17701. Light._INTENSITYMODE_AUTOMATIC = 0;
  17702. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17703. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17704. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17705. Light._INTENSITYMODE_LUMINANCE = 4;
  17706. // Light types ids const.
  17707. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17708. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17709. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17710. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17711. __decorate([
  17712. BABYLON.serializeAsColor3()
  17713. ], Light.prototype, "diffuse", void 0);
  17714. __decorate([
  17715. BABYLON.serializeAsColor3()
  17716. ], Light.prototype, "specular", void 0);
  17717. __decorate([
  17718. BABYLON.serialize()
  17719. ], Light.prototype, "intensity", void 0);
  17720. __decorate([
  17721. BABYLON.serialize()
  17722. ], Light.prototype, "range", void 0);
  17723. __decorate([
  17724. BABYLON.serialize()
  17725. ], Light.prototype, "intensityMode", null);
  17726. __decorate([
  17727. BABYLON.serialize()
  17728. ], Light.prototype, "radius", null);
  17729. __decorate([
  17730. BABYLON.serialize()
  17731. ], Light.prototype, "_renderPriority", void 0);
  17732. __decorate([
  17733. BABYLON.expandToProperty("_reorderLightsInScene")
  17734. ], Light.prototype, "renderPriority", void 0);
  17735. __decorate([
  17736. BABYLON.serialize()
  17737. ], Light.prototype, "shadowEnabled", void 0);
  17738. __decorate([
  17739. BABYLON.serialize("excludeWithLayerMask")
  17740. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17741. __decorate([
  17742. BABYLON.serialize("includeOnlyWithLayerMask")
  17743. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17744. __decorate([
  17745. BABYLON.serialize("lightmapMode")
  17746. ], Light.prototype, "_lightmapMode", void 0);
  17747. return Light;
  17748. }(BABYLON.Node));
  17749. BABYLON.Light = Light;
  17750. })(BABYLON || (BABYLON = {}));
  17751. //# sourceMappingURL=babylon.light.js.map
  17752. var BABYLON;
  17753. (function (BABYLON) {
  17754. var Camera = /** @class */ (function (_super) {
  17755. __extends(Camera, _super);
  17756. function Camera(name, position, scene) {
  17757. var _this = _super.call(this, name, scene) || this;
  17758. /**
  17759. * The vector the camera should consider as up.
  17760. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  17761. */
  17762. _this.upVector = BABYLON.Vector3.Up();
  17763. _this.orthoLeft = null;
  17764. _this.orthoRight = null;
  17765. _this.orthoBottom = null;
  17766. _this.orthoTop = null;
  17767. /**
  17768. * FOV is set in Radians. (default is 0.8)
  17769. */
  17770. _this.fov = 0.8;
  17771. _this.minZ = 1;
  17772. _this.maxZ = 10000.0;
  17773. _this.inertia = 0.9;
  17774. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17775. _this.isIntermediate = false;
  17776. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17777. /**
  17778. * Restricts the camera to viewing objects with the same layerMask.
  17779. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  17780. */
  17781. _this.layerMask = 0x0FFFFFFF;
  17782. /**
  17783. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  17784. */
  17785. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17786. // Camera rig members
  17787. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17788. _this._rigCameras = new Array();
  17789. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17790. _this._skipRendering = false;
  17791. _this.customRenderTargets = new Array();
  17792. // Observables
  17793. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17794. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17795. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17796. _this.onRestoreStateObservable = new BABYLON.Observable();
  17797. // Cache
  17798. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17799. _this._projectionMatrix = new BABYLON.Matrix();
  17800. _this._doNotComputeProjectionMatrix = false;
  17801. _this._postProcesses = new Array();
  17802. _this._transformMatrix = BABYLON.Matrix.Zero();
  17803. _this._activeMeshes = new BABYLON.SmartArray(256);
  17804. _this._globalPosition = BABYLON.Vector3.Zero();
  17805. _this._refreshFrustumPlanes = true;
  17806. _this.getScene().addCamera(_this);
  17807. if (!_this.getScene().activeCamera) {
  17808. _this.getScene().activeCamera = _this;
  17809. }
  17810. _this.position = position;
  17811. return _this;
  17812. }
  17813. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17814. get: function () {
  17815. return Camera._PERSPECTIVE_CAMERA;
  17816. },
  17817. enumerable: true,
  17818. configurable: true
  17819. });
  17820. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17821. get: function () {
  17822. return Camera._ORTHOGRAPHIC_CAMERA;
  17823. },
  17824. enumerable: true,
  17825. configurable: true
  17826. });
  17827. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17828. /**
  17829. * This is the default FOV mode for perspective cameras.
  17830. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17831. *
  17832. */
  17833. get: function () {
  17834. return Camera._FOVMODE_VERTICAL_FIXED;
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17840. /**
  17841. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17842. *
  17843. */
  17844. get: function () {
  17845. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17851. get: function () {
  17852. return Camera._RIG_MODE_NONE;
  17853. },
  17854. enumerable: true,
  17855. configurable: true
  17856. });
  17857. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17858. get: function () {
  17859. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17860. },
  17861. enumerable: true,
  17862. configurable: true
  17863. });
  17864. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17865. get: function () {
  17866. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17872. get: function () {
  17873. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17874. },
  17875. enumerable: true,
  17876. configurable: true
  17877. });
  17878. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17879. get: function () {
  17880. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17886. get: function () {
  17887. return Camera._RIG_MODE_VR;
  17888. },
  17889. enumerable: true,
  17890. configurable: true
  17891. });
  17892. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17893. get: function () {
  17894. return Camera._RIG_MODE_WEBVR;
  17895. },
  17896. enumerable: true,
  17897. configurable: true
  17898. });
  17899. /**
  17900. * Store current camera state (fov, position, etc..)
  17901. */
  17902. Camera.prototype.storeState = function () {
  17903. this._stateStored = true;
  17904. this._storedFov = this.fov;
  17905. return this;
  17906. };
  17907. /**
  17908. * Restores the camera state values if it has been stored. You must call storeState() first
  17909. */
  17910. Camera.prototype._restoreStateValues = function () {
  17911. if (!this._stateStored) {
  17912. return false;
  17913. }
  17914. this.fov = this._storedFov;
  17915. return true;
  17916. };
  17917. /**
  17918. * Restored camera state. You must call storeState() first
  17919. */
  17920. Camera.prototype.restoreState = function () {
  17921. if (this._restoreStateValues()) {
  17922. this.onRestoreStateObservable.notifyObservers(this);
  17923. return true;
  17924. }
  17925. return false;
  17926. };
  17927. Camera.prototype.getClassName = function () {
  17928. return "Camera";
  17929. };
  17930. /**
  17931. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17932. */
  17933. Camera.prototype.toString = function (fullDetails) {
  17934. var ret = "Name: " + this.name;
  17935. ret += ", type: " + this.getClassName();
  17936. if (this.animations) {
  17937. for (var i = 0; i < this.animations.length; i++) {
  17938. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17939. }
  17940. }
  17941. if (fullDetails) {
  17942. }
  17943. return ret;
  17944. };
  17945. Object.defineProperty(Camera.prototype, "globalPosition", {
  17946. get: function () {
  17947. return this._globalPosition;
  17948. },
  17949. enumerable: true,
  17950. configurable: true
  17951. });
  17952. Camera.prototype.getActiveMeshes = function () {
  17953. return this._activeMeshes;
  17954. };
  17955. Camera.prototype.isActiveMesh = function (mesh) {
  17956. return (this._activeMeshes.indexOf(mesh) !== -1);
  17957. };
  17958. //Cache
  17959. Camera.prototype._initCache = function () {
  17960. _super.prototype._initCache.call(this);
  17961. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17962. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17963. this._cache.mode = undefined;
  17964. this._cache.minZ = undefined;
  17965. this._cache.maxZ = undefined;
  17966. this._cache.fov = undefined;
  17967. this._cache.fovMode = undefined;
  17968. this._cache.aspectRatio = undefined;
  17969. this._cache.orthoLeft = undefined;
  17970. this._cache.orthoRight = undefined;
  17971. this._cache.orthoBottom = undefined;
  17972. this._cache.orthoTop = undefined;
  17973. this._cache.renderWidth = undefined;
  17974. this._cache.renderHeight = undefined;
  17975. };
  17976. Camera.prototype._updateCache = function (ignoreParentClass) {
  17977. if (!ignoreParentClass) {
  17978. _super.prototype._updateCache.call(this);
  17979. }
  17980. this._cache.position.copyFrom(this.position);
  17981. this._cache.upVector.copyFrom(this.upVector);
  17982. };
  17983. // Synchronized
  17984. Camera.prototype._isSynchronized = function () {
  17985. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17986. };
  17987. Camera.prototype._isSynchronizedViewMatrix = function () {
  17988. if (!_super.prototype._isSynchronized.call(this))
  17989. return false;
  17990. return this._cache.position.equals(this.position)
  17991. && this._cache.upVector.equals(this.upVector)
  17992. && this.isSynchronizedWithParent();
  17993. };
  17994. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17995. var check = this._cache.mode === this.mode
  17996. && this._cache.minZ === this.minZ
  17997. && this._cache.maxZ === this.maxZ;
  17998. if (!check) {
  17999. return false;
  18000. }
  18001. var engine = this.getEngine();
  18002. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18003. check = this._cache.fov === this.fov
  18004. && this._cache.fovMode === this.fovMode
  18005. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18006. }
  18007. else {
  18008. check = this._cache.orthoLeft === this.orthoLeft
  18009. && this._cache.orthoRight === this.orthoRight
  18010. && this._cache.orthoBottom === this.orthoBottom
  18011. && this._cache.orthoTop === this.orthoTop
  18012. && this._cache.renderWidth === engine.getRenderWidth()
  18013. && this._cache.renderHeight === engine.getRenderHeight();
  18014. }
  18015. return check;
  18016. };
  18017. // Controls
  18018. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18019. };
  18020. Camera.prototype.detachControl = function (element) {
  18021. };
  18022. Camera.prototype.update = function () {
  18023. this._checkInputs();
  18024. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18025. this._updateRigCameras();
  18026. }
  18027. };
  18028. Camera.prototype._checkInputs = function () {
  18029. this.onAfterCheckInputsObservable.notifyObservers(this);
  18030. };
  18031. Object.defineProperty(Camera.prototype, "rigCameras", {
  18032. get: function () {
  18033. return this._rigCameras;
  18034. },
  18035. enumerable: true,
  18036. configurable: true
  18037. });
  18038. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18039. get: function () {
  18040. return this._rigPostProcess;
  18041. },
  18042. enumerable: true,
  18043. configurable: true
  18044. });
  18045. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18046. // invalidate framebuffer
  18047. if (this._postProcesses.length > 0) {
  18048. this._postProcesses[0].markTextureDirty();
  18049. }
  18050. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18051. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18052. var cam = this._rigCameras[i];
  18053. var rigPostProcess = cam._rigPostProcess;
  18054. // for VR rig, there does not have to be a post process
  18055. if (rigPostProcess) {
  18056. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18057. if (isPass) {
  18058. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18059. cam.isIntermediate = this._postProcesses.length === 0;
  18060. }
  18061. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18062. rigPostProcess.markTextureDirty();
  18063. }
  18064. else {
  18065. cam._postProcesses = this._postProcesses.slice(0);
  18066. }
  18067. }
  18068. };
  18069. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18070. if (insertAt === void 0) { insertAt = null; }
  18071. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18072. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18073. return 0;
  18074. }
  18075. if (insertAt == null || insertAt < 0) {
  18076. this._postProcesses.push(postProcess);
  18077. }
  18078. else {
  18079. this._postProcesses.splice(insertAt, 0, postProcess);
  18080. }
  18081. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18082. return this._postProcesses.indexOf(postProcess);
  18083. };
  18084. Camera.prototype.detachPostProcess = function (postProcess) {
  18085. var idx = this._postProcesses.indexOf(postProcess);
  18086. if (idx !== -1) {
  18087. this._postProcesses.splice(idx, 1);
  18088. }
  18089. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18090. };
  18091. Camera.prototype.getWorldMatrix = function () {
  18092. if (!this._worldMatrix) {
  18093. this._worldMatrix = BABYLON.Matrix.Identity();
  18094. }
  18095. var viewMatrix = this.getViewMatrix();
  18096. viewMatrix.invertToRef(this._worldMatrix);
  18097. return this._worldMatrix;
  18098. };
  18099. Camera.prototype._getViewMatrix = function () {
  18100. return BABYLON.Matrix.Identity();
  18101. };
  18102. Camera.prototype.getViewMatrix = function (force) {
  18103. if (!force && this._isSynchronizedViewMatrix()) {
  18104. return this._computedViewMatrix;
  18105. }
  18106. this.updateCache();
  18107. this._computedViewMatrix = this._getViewMatrix();
  18108. this._currentRenderId = this.getScene().getRenderId();
  18109. this._refreshFrustumPlanes = true;
  18110. if (!this.parent || !this.parent.getWorldMatrix) {
  18111. this._globalPosition.copyFrom(this.position);
  18112. }
  18113. else {
  18114. if (!this._worldMatrix) {
  18115. this._worldMatrix = BABYLON.Matrix.Identity();
  18116. }
  18117. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18118. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18119. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18120. this._computedViewMatrix.invert();
  18121. this._markSyncedWithParent();
  18122. }
  18123. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18124. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18125. }
  18126. this.onViewMatrixChangedObservable.notifyObservers(this);
  18127. return this._computedViewMatrix;
  18128. };
  18129. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18130. this._doNotComputeProjectionMatrix = true;
  18131. if (projection !== undefined) {
  18132. this._projectionMatrix = projection;
  18133. }
  18134. };
  18135. ;
  18136. Camera.prototype.unfreezeProjectionMatrix = function () {
  18137. this._doNotComputeProjectionMatrix = false;
  18138. };
  18139. ;
  18140. Camera.prototype.getProjectionMatrix = function (force) {
  18141. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18142. return this._projectionMatrix;
  18143. }
  18144. // Cache
  18145. this._cache.mode = this.mode;
  18146. this._cache.minZ = this.minZ;
  18147. this._cache.maxZ = this.maxZ;
  18148. // Matrix
  18149. this._refreshFrustumPlanes = true;
  18150. var engine = this.getEngine();
  18151. var scene = this.getScene();
  18152. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18153. this._cache.fov = this.fov;
  18154. this._cache.fovMode = this.fovMode;
  18155. this._cache.aspectRatio = engine.getAspectRatio(this);
  18156. if (this.minZ <= 0) {
  18157. this.minZ = 0.1;
  18158. }
  18159. if (scene.useRightHandedSystem) {
  18160. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18161. }
  18162. else {
  18163. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18164. }
  18165. }
  18166. else {
  18167. var halfWidth = engine.getRenderWidth() / 2.0;
  18168. var halfHeight = engine.getRenderHeight() / 2.0;
  18169. if (scene.useRightHandedSystem) {
  18170. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18171. }
  18172. else {
  18173. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18174. }
  18175. this._cache.orthoLeft = this.orthoLeft;
  18176. this._cache.orthoRight = this.orthoRight;
  18177. this._cache.orthoBottom = this.orthoBottom;
  18178. this._cache.orthoTop = this.orthoTop;
  18179. this._cache.renderWidth = engine.getRenderWidth();
  18180. this._cache.renderHeight = engine.getRenderHeight();
  18181. }
  18182. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18183. return this._projectionMatrix;
  18184. };
  18185. Camera.prototype.getTranformationMatrix = function () {
  18186. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18187. return this._transformMatrix;
  18188. };
  18189. Camera.prototype.updateFrustumPlanes = function () {
  18190. if (!this._refreshFrustumPlanes) {
  18191. return;
  18192. }
  18193. this.getTranformationMatrix();
  18194. if (!this._frustumPlanes) {
  18195. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18196. }
  18197. else {
  18198. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18199. }
  18200. this._refreshFrustumPlanes = false;
  18201. };
  18202. Camera.prototype.isInFrustum = function (target) {
  18203. this.updateFrustumPlanes();
  18204. return target.isInFrustum(this._frustumPlanes);
  18205. };
  18206. Camera.prototype.isCompletelyInFrustum = function (target) {
  18207. this.updateFrustumPlanes();
  18208. return target.isCompletelyInFrustum(this._frustumPlanes);
  18209. };
  18210. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18211. if (length === void 0) { length = 100; }
  18212. if (!transform) {
  18213. transform = this.getWorldMatrix();
  18214. }
  18215. if (!origin) {
  18216. origin = this.position;
  18217. }
  18218. var forward = new BABYLON.Vector3(0, 0, 1);
  18219. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18220. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18221. return new BABYLON.Ray(origin, direction, length);
  18222. };
  18223. Camera.prototype.dispose = function () {
  18224. // Observables
  18225. this.onViewMatrixChangedObservable.clear();
  18226. this.onProjectionMatrixChangedObservable.clear();
  18227. this.onAfterCheckInputsObservable.clear();
  18228. this.onRestoreStateObservable.clear();
  18229. // Inputs
  18230. if (this.inputs) {
  18231. this.inputs.clear();
  18232. }
  18233. // Animations
  18234. this.getScene().stopAnimation(this);
  18235. // Remove from scene
  18236. this.getScene().removeCamera(this);
  18237. while (this._rigCameras.length > 0) {
  18238. var camera = this._rigCameras.pop();
  18239. if (camera) {
  18240. camera.dispose();
  18241. }
  18242. }
  18243. // Postprocesses
  18244. if (this._rigPostProcess) {
  18245. this._rigPostProcess.dispose(this);
  18246. this._rigPostProcess = null;
  18247. this._postProcesses = [];
  18248. }
  18249. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18250. this._rigPostProcess = null;
  18251. this._postProcesses = [];
  18252. }
  18253. else {
  18254. var i = this._postProcesses.length;
  18255. while (--i >= 0) {
  18256. this._postProcesses[i].dispose(this);
  18257. }
  18258. }
  18259. // Render targets
  18260. var i = this.customRenderTargets.length;
  18261. while (--i >= 0) {
  18262. this.customRenderTargets[i].dispose();
  18263. }
  18264. this.customRenderTargets = [];
  18265. // Active Meshes
  18266. this._activeMeshes.dispose();
  18267. _super.prototype.dispose.call(this);
  18268. };
  18269. Object.defineProperty(Camera.prototype, "leftCamera", {
  18270. // ---- Camera rigs section ----
  18271. get: function () {
  18272. if (this._rigCameras.length < 1) {
  18273. return null;
  18274. }
  18275. return this._rigCameras[0];
  18276. },
  18277. enumerable: true,
  18278. configurable: true
  18279. });
  18280. Object.defineProperty(Camera.prototype, "rightCamera", {
  18281. get: function () {
  18282. if (this._rigCameras.length < 2) {
  18283. return null;
  18284. }
  18285. return this._rigCameras[1];
  18286. },
  18287. enumerable: true,
  18288. configurable: true
  18289. });
  18290. Camera.prototype.getLeftTarget = function () {
  18291. if (this._rigCameras.length < 1) {
  18292. return null;
  18293. }
  18294. return this._rigCameras[0].getTarget();
  18295. };
  18296. Camera.prototype.getRightTarget = function () {
  18297. if (this._rigCameras.length < 2) {
  18298. return null;
  18299. }
  18300. return this._rigCameras[1].getTarget();
  18301. };
  18302. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18303. if (this.cameraRigMode === mode) {
  18304. return;
  18305. }
  18306. while (this._rigCameras.length > 0) {
  18307. var camera = this._rigCameras.pop();
  18308. if (camera) {
  18309. camera.dispose();
  18310. }
  18311. }
  18312. this.cameraRigMode = mode;
  18313. this._cameraRigParams = {};
  18314. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18315. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18316. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18317. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18318. // create the rig cameras, unless none
  18319. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18320. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18321. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18322. if (leftCamera && rightCamera) {
  18323. this._rigCameras.push(leftCamera);
  18324. this._rigCameras.push(rightCamera);
  18325. }
  18326. }
  18327. switch (this.cameraRigMode) {
  18328. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18329. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18330. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18331. break;
  18332. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18333. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18334. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18335. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18336. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18337. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18338. break;
  18339. case Camera.RIG_MODE_VR:
  18340. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18341. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18342. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18343. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18344. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18345. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18346. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18347. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18348. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18349. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18350. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18351. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18352. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18353. if (metrics.compensateDistortion) {
  18354. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18355. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18356. }
  18357. break;
  18358. case Camera.RIG_MODE_WEBVR:
  18359. if (rigParams.vrDisplay) {
  18360. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18361. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18362. //Left eye
  18363. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18364. this._rigCameras[0].setCameraRigParameter("left", true);
  18365. //leaving this for future reference
  18366. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18367. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18368. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18369. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18370. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18371. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18372. this._rigCameras[0].parent = this;
  18373. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18374. //Right eye
  18375. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18376. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18377. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18378. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18379. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18380. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18381. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18382. this._rigCameras[1].parent = this;
  18383. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18384. if (Camera.UseAlternateWebVRRendering) {
  18385. this._rigCameras[1]._skipRendering = true;
  18386. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18387. }
  18388. }
  18389. break;
  18390. }
  18391. this._cascadePostProcessesToRigCams();
  18392. this.update();
  18393. };
  18394. Camera.prototype._getVRProjectionMatrix = function () {
  18395. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18396. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18397. return this._projectionMatrix;
  18398. };
  18399. Camera.prototype._updateCameraRotationMatrix = function () {
  18400. //Here for WebVR
  18401. };
  18402. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18403. //Here for WebVR
  18404. };
  18405. /**
  18406. * This function MUST be overwritten by the different WebVR cameras available.
  18407. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18408. */
  18409. Camera.prototype._getWebVRProjectionMatrix = function () {
  18410. return BABYLON.Matrix.Identity();
  18411. };
  18412. /**
  18413. * This function MUST be overwritten by the different WebVR cameras available.
  18414. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18415. */
  18416. Camera.prototype._getWebVRViewMatrix = function () {
  18417. return BABYLON.Matrix.Identity();
  18418. };
  18419. Camera.prototype.setCameraRigParameter = function (name, value) {
  18420. if (!this._cameraRigParams) {
  18421. this._cameraRigParams = {};
  18422. }
  18423. this._cameraRigParams[name] = value;
  18424. //provisionnally:
  18425. if (name === "interaxialDistance") {
  18426. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18427. }
  18428. };
  18429. /**
  18430. * needs to be overridden by children so sub has required properties to be copied
  18431. */
  18432. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18433. return null;
  18434. };
  18435. /**
  18436. * May need to be overridden by children
  18437. */
  18438. Camera.prototype._updateRigCameras = function () {
  18439. for (var i = 0; i < this._rigCameras.length; i++) {
  18440. this._rigCameras[i].minZ = this.minZ;
  18441. this._rigCameras[i].maxZ = this.maxZ;
  18442. this._rigCameras[i].fov = this.fov;
  18443. }
  18444. // only update viewport when ANAGLYPH
  18445. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18446. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18447. }
  18448. };
  18449. Camera.prototype._setupInputs = function () {
  18450. };
  18451. Camera.prototype.serialize = function () {
  18452. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18453. // Type
  18454. serializationObject.type = this.getClassName();
  18455. // Parent
  18456. if (this.parent) {
  18457. serializationObject.parentId = this.parent.id;
  18458. }
  18459. if (this.inputs) {
  18460. this.inputs.serialize(serializationObject);
  18461. }
  18462. // Animations
  18463. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18464. serializationObject.ranges = this.serializeAnimationRanges();
  18465. return serializationObject;
  18466. };
  18467. Camera.prototype.clone = function (name) {
  18468. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18469. };
  18470. Camera.prototype.getDirection = function (localAxis) {
  18471. var result = BABYLON.Vector3.Zero();
  18472. this.getDirectionToRef(localAxis, result);
  18473. return result;
  18474. };
  18475. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18476. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18477. };
  18478. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18479. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18480. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18481. switch (type) {
  18482. case "ArcRotateCamera":
  18483. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18484. case "DeviceOrientationCamera":
  18485. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18486. case "FollowCamera":
  18487. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18488. case "ArcFollowCamera":
  18489. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18490. case "GamepadCamera":
  18491. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18492. case "TouchCamera":
  18493. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18494. case "VirtualJoysticksCamera":
  18495. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18496. case "WebVRFreeCamera":
  18497. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18498. case "WebVRGamepadCamera":
  18499. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18500. case "VRDeviceOrientationFreeCamera":
  18501. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18502. case "VRDeviceOrientationGamepadCamera":
  18503. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18504. case "AnaglyphArcRotateCamera":
  18505. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18506. case "AnaglyphFreeCamera":
  18507. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18508. case "AnaglyphGamepadCamera":
  18509. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18510. case "AnaglyphUniversalCamera":
  18511. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18512. case "StereoscopicArcRotateCamera":
  18513. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18514. case "StereoscopicFreeCamera":
  18515. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18516. case "StereoscopicGamepadCamera":
  18517. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18518. case "StereoscopicUniversalCamera":
  18519. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18520. case "FreeCamera":// Forcing Universal here
  18521. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18522. default:// Universal Camera is the default value
  18523. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18524. }
  18525. };
  18526. Camera.prototype.computeWorldMatrix = function () {
  18527. return this.getWorldMatrix();
  18528. };
  18529. Camera.Parse = function (parsedCamera, scene) {
  18530. var type = parsedCamera.type;
  18531. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18532. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18533. // Parent
  18534. if (parsedCamera.parentId) {
  18535. camera._waitingParentId = parsedCamera.parentId;
  18536. }
  18537. //If camera has an input manager, let it parse inputs settings
  18538. if (camera.inputs) {
  18539. camera.inputs.parse(parsedCamera);
  18540. camera._setupInputs();
  18541. }
  18542. if (camera.setPosition) {
  18543. camera.position.copyFromFloats(0, 0, 0);
  18544. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18545. }
  18546. // Target
  18547. if (parsedCamera.target) {
  18548. if (camera.setTarget) {
  18549. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18550. }
  18551. }
  18552. // Apply 3d rig, when found
  18553. if (parsedCamera.cameraRigMode) {
  18554. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18555. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18556. }
  18557. // Animations
  18558. if (parsedCamera.animations) {
  18559. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18560. var parsedAnimation = parsedCamera.animations[animationIndex];
  18561. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18562. }
  18563. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18564. }
  18565. if (parsedCamera.autoAnimate) {
  18566. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18567. }
  18568. return camera;
  18569. };
  18570. // Statics
  18571. Camera._PERSPECTIVE_CAMERA = 0;
  18572. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18573. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18574. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18575. Camera._RIG_MODE_NONE = 0;
  18576. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18577. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18578. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18579. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18580. Camera._RIG_MODE_VR = 20;
  18581. Camera._RIG_MODE_WEBVR = 21;
  18582. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18583. Camera.UseAlternateWebVRRendering = false;
  18584. __decorate([
  18585. BABYLON.serializeAsVector3()
  18586. ], Camera.prototype, "position", void 0);
  18587. __decorate([
  18588. BABYLON.serializeAsVector3()
  18589. ], Camera.prototype, "upVector", void 0);
  18590. __decorate([
  18591. BABYLON.serialize()
  18592. ], Camera.prototype, "orthoLeft", void 0);
  18593. __decorate([
  18594. BABYLON.serialize()
  18595. ], Camera.prototype, "orthoRight", void 0);
  18596. __decorate([
  18597. BABYLON.serialize()
  18598. ], Camera.prototype, "orthoBottom", void 0);
  18599. __decorate([
  18600. BABYLON.serialize()
  18601. ], Camera.prototype, "orthoTop", void 0);
  18602. __decorate([
  18603. BABYLON.serialize()
  18604. ], Camera.prototype, "fov", void 0);
  18605. __decorate([
  18606. BABYLON.serialize()
  18607. ], Camera.prototype, "minZ", void 0);
  18608. __decorate([
  18609. BABYLON.serialize()
  18610. ], Camera.prototype, "maxZ", void 0);
  18611. __decorate([
  18612. BABYLON.serialize()
  18613. ], Camera.prototype, "inertia", void 0);
  18614. __decorate([
  18615. BABYLON.serialize()
  18616. ], Camera.prototype, "mode", void 0);
  18617. __decorate([
  18618. BABYLON.serialize()
  18619. ], Camera.prototype, "layerMask", void 0);
  18620. __decorate([
  18621. BABYLON.serialize()
  18622. ], Camera.prototype, "fovMode", void 0);
  18623. __decorate([
  18624. BABYLON.serialize()
  18625. ], Camera.prototype, "cameraRigMode", void 0);
  18626. __decorate([
  18627. BABYLON.serialize()
  18628. ], Camera.prototype, "interaxialDistance", void 0);
  18629. __decorate([
  18630. BABYLON.serialize()
  18631. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18632. return Camera;
  18633. }(BABYLON.Node));
  18634. BABYLON.Camera = Camera;
  18635. })(BABYLON || (BABYLON = {}));
  18636. //# sourceMappingURL=babylon.camera.js.map
  18637. var BABYLON;
  18638. (function (BABYLON) {
  18639. var RenderingManager = /** @class */ (function () {
  18640. function RenderingManager(scene) {
  18641. this._renderingGroups = new Array();
  18642. this._autoClearDepthStencil = {};
  18643. this._customOpaqueSortCompareFn = {};
  18644. this._customAlphaTestSortCompareFn = {};
  18645. this._customTransparentSortCompareFn = {};
  18646. this._renderinGroupInfo = null;
  18647. this._scene = scene;
  18648. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18649. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18650. }
  18651. }
  18652. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18653. if (depth === void 0) { depth = true; }
  18654. if (stencil === void 0) { stencil = true; }
  18655. if (this._depthStencilBufferAlreadyCleaned) {
  18656. return;
  18657. }
  18658. this._scene.getEngine().clear(null, false, depth, stencil);
  18659. this._depthStencilBufferAlreadyCleaned = true;
  18660. };
  18661. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18662. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18663. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18664. var info = null;
  18665. if (observable) {
  18666. if (!this._renderinGroupInfo) {
  18667. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18668. }
  18669. info = this._renderinGroupInfo;
  18670. info.scene = this._scene;
  18671. info.camera = this._scene.activeCamera;
  18672. }
  18673. // Dispatch sprites
  18674. if (renderSprites) {
  18675. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18676. var manager = this._scene.spriteManagers[index];
  18677. this.dispatchSprites(manager);
  18678. }
  18679. }
  18680. // Render
  18681. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18682. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18683. var renderingGroup = this._renderingGroups[index];
  18684. if (!renderingGroup && !observable)
  18685. continue;
  18686. var renderingGroupMask = 0;
  18687. // Fire PRECLEAR stage
  18688. if (observable && info) {
  18689. renderingGroupMask = Math.pow(2, index);
  18690. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18691. info.renderingGroupId = index;
  18692. observable.notifyObservers(info, renderingGroupMask);
  18693. }
  18694. // Clear depth/stencil if needed
  18695. if (RenderingManager.AUTOCLEAR) {
  18696. var autoClear = this._autoClearDepthStencil[index];
  18697. if (autoClear && autoClear.autoClear) {
  18698. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18699. }
  18700. }
  18701. if (observable && info) {
  18702. // Fire PREOPAQUE stage
  18703. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18704. observable.notifyObservers(info, renderingGroupMask);
  18705. // Fire PRETRANSPARENT stage
  18706. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18707. observable.notifyObservers(info, renderingGroupMask);
  18708. }
  18709. if (renderingGroup)
  18710. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18711. // Fire POSTTRANSPARENT stage
  18712. if (observable && info) {
  18713. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18714. observable.notifyObservers(info, renderingGroupMask);
  18715. }
  18716. }
  18717. };
  18718. RenderingManager.prototype.reset = function () {
  18719. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18720. var renderingGroup = this._renderingGroups[index];
  18721. if (renderingGroup) {
  18722. renderingGroup.prepare();
  18723. }
  18724. }
  18725. };
  18726. RenderingManager.prototype.dispose = function () {
  18727. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18728. var renderingGroup = this._renderingGroups[index];
  18729. if (renderingGroup) {
  18730. renderingGroup.dispose();
  18731. }
  18732. }
  18733. this._renderingGroups.length = 0;
  18734. };
  18735. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18736. if (this._renderingGroups[renderingGroupId] === undefined) {
  18737. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18738. }
  18739. };
  18740. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18741. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18742. this._prepareRenderingGroup(renderingGroupId);
  18743. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18744. };
  18745. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18746. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18747. this._prepareRenderingGroup(renderingGroupId);
  18748. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18749. };
  18750. /**
  18751. * @param subMesh The submesh to dispatch
  18752. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18753. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18754. */
  18755. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18756. if (mesh === undefined) {
  18757. mesh = subMesh.getMesh();
  18758. }
  18759. var renderingGroupId = mesh.renderingGroupId || 0;
  18760. this._prepareRenderingGroup(renderingGroupId);
  18761. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18762. };
  18763. /**
  18764. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18765. * This allowed control for front to back rendering or reversly depending of the special needs.
  18766. *
  18767. * @param renderingGroupId The rendering group id corresponding to its index
  18768. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18769. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18770. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18771. */
  18772. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18773. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18774. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18775. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18776. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18777. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18778. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18779. if (this._renderingGroups[renderingGroupId]) {
  18780. var group = this._renderingGroups[renderingGroupId];
  18781. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18782. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18783. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18784. }
  18785. };
  18786. /**
  18787. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18788. *
  18789. * @param renderingGroupId The rendering group id corresponding to its index
  18790. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18791. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18792. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18793. */
  18794. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18795. if (depth === void 0) { depth = true; }
  18796. if (stencil === void 0) { stencil = true; }
  18797. this._autoClearDepthStencil[renderingGroupId] = {
  18798. autoClear: autoClearDepthStencil,
  18799. depth: depth,
  18800. stencil: stencil
  18801. };
  18802. };
  18803. /**
  18804. * The max id used for rendering groups (not included)
  18805. */
  18806. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18807. /**
  18808. * The min id used for rendering groups (included)
  18809. */
  18810. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18811. /**
  18812. * Used to globally prevent autoclearing scenes.
  18813. */
  18814. RenderingManager.AUTOCLEAR = true;
  18815. return RenderingManager;
  18816. }());
  18817. BABYLON.RenderingManager = RenderingManager;
  18818. })(BABYLON || (BABYLON = {}));
  18819. //# sourceMappingURL=babylon.renderingManager.js.map
  18820. var BABYLON;
  18821. (function (BABYLON) {
  18822. var RenderingGroup = /** @class */ (function () {
  18823. /**
  18824. * Creates a new rendering group.
  18825. * @param index The rendering group index
  18826. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18827. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18828. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18829. */
  18830. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18831. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18832. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18833. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18834. this.index = index;
  18835. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18836. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18837. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18838. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18839. this._particleSystems = new BABYLON.SmartArray(256);
  18840. this._spriteManagers = new BABYLON.SmartArray(256);
  18841. this._edgesRenderers = new BABYLON.SmartArray(16);
  18842. this._scene = scene;
  18843. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18844. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18845. this.transparentSortCompareFn = transparentSortCompareFn;
  18846. }
  18847. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18848. /**
  18849. * Set the opaque sort comparison function.
  18850. * If null the sub meshes will be render in the order they were created
  18851. */
  18852. set: function (value) {
  18853. this._opaqueSortCompareFn = value;
  18854. if (value) {
  18855. this._renderOpaque = this.renderOpaqueSorted;
  18856. }
  18857. else {
  18858. this._renderOpaque = RenderingGroup.renderUnsorted;
  18859. }
  18860. },
  18861. enumerable: true,
  18862. configurable: true
  18863. });
  18864. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18865. /**
  18866. * Set the alpha test sort comparison function.
  18867. * If null the sub meshes will be render in the order they were created
  18868. */
  18869. set: function (value) {
  18870. this._alphaTestSortCompareFn = value;
  18871. if (value) {
  18872. this._renderAlphaTest = this.renderAlphaTestSorted;
  18873. }
  18874. else {
  18875. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18876. }
  18877. },
  18878. enumerable: true,
  18879. configurable: true
  18880. });
  18881. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18882. /**
  18883. * Set the transparent sort comparison function.
  18884. * If null the sub meshes will be render in the order they were created
  18885. */
  18886. set: function (value) {
  18887. if (value) {
  18888. this._transparentSortCompareFn = value;
  18889. }
  18890. else {
  18891. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18892. }
  18893. this._renderTransparent = this.renderTransparentSorted;
  18894. },
  18895. enumerable: true,
  18896. configurable: true
  18897. });
  18898. /**
  18899. * Render all the sub meshes contained in the group.
  18900. * @param customRenderFunction Used to override the default render behaviour of the group.
  18901. * @returns true if rendered some submeshes.
  18902. */
  18903. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18904. if (customRenderFunction) {
  18905. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18906. return;
  18907. }
  18908. var engine = this._scene.getEngine();
  18909. // Depth only
  18910. if (this._depthOnlySubMeshes.length !== 0) {
  18911. engine.setColorWrite(false);
  18912. this._renderAlphaTest(this._depthOnlySubMeshes);
  18913. engine.setColorWrite(true);
  18914. }
  18915. // Opaque
  18916. if (this._opaqueSubMeshes.length !== 0) {
  18917. this._renderOpaque(this._opaqueSubMeshes);
  18918. }
  18919. // Alpha test
  18920. if (this._alphaTestSubMeshes.length !== 0) {
  18921. this._renderAlphaTest(this._alphaTestSubMeshes);
  18922. }
  18923. var stencilState = engine.getStencilBuffer();
  18924. engine.setStencilBuffer(false);
  18925. // Sprites
  18926. if (renderSprites) {
  18927. this._renderSprites();
  18928. }
  18929. // Particles
  18930. if (renderParticles) {
  18931. this._renderParticles(activeMeshes);
  18932. }
  18933. if (this.onBeforeTransparentRendering) {
  18934. this.onBeforeTransparentRendering();
  18935. }
  18936. // Transparent
  18937. if (this._transparentSubMeshes.length !== 0) {
  18938. this._renderTransparent(this._transparentSubMeshes);
  18939. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18940. }
  18941. // Set back stencil to false in case it changes before the edge renderer.
  18942. engine.setStencilBuffer(false);
  18943. // Edges
  18944. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18945. this._edgesRenderers.data[edgesRendererIndex].render();
  18946. }
  18947. // Restore Stencil state.
  18948. engine.setStencilBuffer(stencilState);
  18949. };
  18950. /**
  18951. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18952. * @param subMeshes The submeshes to render
  18953. */
  18954. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18955. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18956. };
  18957. /**
  18958. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18959. * @param subMeshes The submeshes to render
  18960. */
  18961. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18962. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18963. };
  18964. /**
  18965. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18966. * @param subMeshes The submeshes to render
  18967. */
  18968. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18969. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18970. };
  18971. /**
  18972. * Renders the submeshes in a specified order.
  18973. * @param subMeshes The submeshes to sort before render
  18974. * @param sortCompareFn The comparison function use to sort
  18975. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18976. * @param transparent Specifies to activate blending if true
  18977. */
  18978. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18979. var subIndex = 0;
  18980. var subMesh;
  18981. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18982. for (; subIndex < subMeshes.length; subIndex++) {
  18983. subMesh = subMeshes.data[subIndex];
  18984. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18985. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18986. }
  18987. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18988. if (sortCompareFn) {
  18989. sortedArray.sort(sortCompareFn);
  18990. }
  18991. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18992. subMesh = sortedArray[subIndex];
  18993. if (transparent) {
  18994. var material = subMesh.getMaterial();
  18995. if (material && material.needDepthPrePass) {
  18996. var engine = material.getScene().getEngine();
  18997. engine.setColorWrite(false);
  18998. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18999. subMesh.render(false);
  19000. engine.setColorWrite(true);
  19001. }
  19002. }
  19003. subMesh.render(transparent);
  19004. }
  19005. };
  19006. /**
  19007. * Renders the submeshes in the order they were dispatched (no sort applied).
  19008. * @param subMeshes The submeshes to render
  19009. */
  19010. RenderingGroup.renderUnsorted = function (subMeshes) {
  19011. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19012. var submesh = subMeshes.data[subIndex];
  19013. submesh.render(false);
  19014. }
  19015. };
  19016. /**
  19017. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19018. * are rendered back to front if in the same alpha index.
  19019. *
  19020. * @param a The first submesh
  19021. * @param b The second submesh
  19022. * @returns The result of the comparison
  19023. */
  19024. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19025. // Alpha index first
  19026. if (a._alphaIndex > b._alphaIndex) {
  19027. return 1;
  19028. }
  19029. if (a._alphaIndex < b._alphaIndex) {
  19030. return -1;
  19031. }
  19032. // Then distance to camera
  19033. return RenderingGroup.backToFrontSortCompare(a, b);
  19034. };
  19035. /**
  19036. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19037. * are rendered back to front.
  19038. *
  19039. * @param a The first submesh
  19040. * @param b The second submesh
  19041. * @returns The result of the comparison
  19042. */
  19043. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19044. // Then distance to camera
  19045. if (a._distanceToCamera < b._distanceToCamera) {
  19046. return 1;
  19047. }
  19048. if (a._distanceToCamera > b._distanceToCamera) {
  19049. return -1;
  19050. }
  19051. return 0;
  19052. };
  19053. /**
  19054. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19055. * are rendered front to back (prevent overdraw).
  19056. *
  19057. * @param a The first submesh
  19058. * @param b The second submesh
  19059. * @returns The result of the comparison
  19060. */
  19061. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19062. // Then distance to camera
  19063. if (a._distanceToCamera < b._distanceToCamera) {
  19064. return -1;
  19065. }
  19066. if (a._distanceToCamera > b._distanceToCamera) {
  19067. return 1;
  19068. }
  19069. return 0;
  19070. };
  19071. /**
  19072. * Resets the different lists of submeshes to prepare a new frame.
  19073. */
  19074. RenderingGroup.prototype.prepare = function () {
  19075. this._opaqueSubMeshes.reset();
  19076. this._transparentSubMeshes.reset();
  19077. this._alphaTestSubMeshes.reset();
  19078. this._depthOnlySubMeshes.reset();
  19079. this._particleSystems.reset();
  19080. this._spriteManagers.reset();
  19081. this._edgesRenderers.reset();
  19082. };
  19083. RenderingGroup.prototype.dispose = function () {
  19084. this._opaqueSubMeshes.dispose();
  19085. this._transparentSubMeshes.dispose();
  19086. this._alphaTestSubMeshes.dispose();
  19087. this._depthOnlySubMeshes.dispose();
  19088. this._particleSystems.dispose();
  19089. this._spriteManagers.dispose();
  19090. this._edgesRenderers.dispose();
  19091. };
  19092. /**
  19093. * Inserts the submesh in its correct queue depending on its material.
  19094. * @param subMesh The submesh to dispatch
  19095. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19096. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19097. */
  19098. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19099. // Get mesh and materials if not provided
  19100. if (mesh === undefined) {
  19101. mesh = subMesh.getMesh();
  19102. }
  19103. if (material === undefined) {
  19104. material = subMesh.getMaterial();
  19105. }
  19106. if (material === null || material === undefined) {
  19107. return;
  19108. }
  19109. if (material.needAlphaBlendingForMesh(mesh)) {
  19110. this._transparentSubMeshes.push(subMesh);
  19111. }
  19112. else if (material.needAlphaTesting()) {
  19113. if (material.needDepthPrePass) {
  19114. this._depthOnlySubMeshes.push(subMesh);
  19115. }
  19116. this._alphaTestSubMeshes.push(subMesh);
  19117. }
  19118. else {
  19119. if (material.needDepthPrePass) {
  19120. this._depthOnlySubMeshes.push(subMesh);
  19121. }
  19122. this._opaqueSubMeshes.push(subMesh); // Opaque
  19123. }
  19124. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19125. this._edgesRenderers.push(mesh._edgesRenderer);
  19126. }
  19127. };
  19128. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19129. this._spriteManagers.push(spriteManager);
  19130. };
  19131. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19132. this._particleSystems.push(particleSystem);
  19133. };
  19134. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19135. if (this._particleSystems.length === 0) {
  19136. return;
  19137. }
  19138. // Particles
  19139. var activeCamera = this._scene.activeCamera;
  19140. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19141. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19142. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19143. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19144. continue;
  19145. }
  19146. var emitter = particleSystem.emitter;
  19147. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19148. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19149. }
  19150. }
  19151. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19152. };
  19153. RenderingGroup.prototype._renderSprites = function () {
  19154. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19155. return;
  19156. }
  19157. // Sprites
  19158. var activeCamera = this._scene.activeCamera;
  19159. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19160. for (var id = 0; id < this._spriteManagers.length; id++) {
  19161. var spriteManager = this._spriteManagers.data[id];
  19162. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19163. spriteManager.render();
  19164. }
  19165. }
  19166. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19167. };
  19168. return RenderingGroup;
  19169. }());
  19170. BABYLON.RenderingGroup = RenderingGroup;
  19171. })(BABYLON || (BABYLON = {}));
  19172. //# sourceMappingURL=babylon.renderingGroup.js.map
  19173. var BABYLON;
  19174. (function (BABYLON) {
  19175. var ClickInfo = /** @class */ (function () {
  19176. function ClickInfo() {
  19177. this._singleClick = false;
  19178. this._doubleClick = false;
  19179. this._hasSwiped = false;
  19180. this._ignore = false;
  19181. }
  19182. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19183. get: function () {
  19184. return this._singleClick;
  19185. },
  19186. set: function (b) {
  19187. this._singleClick = b;
  19188. },
  19189. enumerable: true,
  19190. configurable: true
  19191. });
  19192. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19193. get: function () {
  19194. return this._doubleClick;
  19195. },
  19196. set: function (b) {
  19197. this._doubleClick = b;
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19203. get: function () {
  19204. return this._hasSwiped;
  19205. },
  19206. set: function (b) {
  19207. this._hasSwiped = b;
  19208. },
  19209. enumerable: true,
  19210. configurable: true
  19211. });
  19212. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19213. get: function () {
  19214. return this._ignore;
  19215. },
  19216. set: function (b) {
  19217. this._ignore = b;
  19218. },
  19219. enumerable: true,
  19220. configurable: true
  19221. });
  19222. return ClickInfo;
  19223. }());
  19224. /**
  19225. * This class is used by the onRenderingGroupObservable
  19226. */
  19227. var RenderingGroupInfo = /** @class */ (function () {
  19228. function RenderingGroupInfo() {
  19229. }
  19230. /**
  19231. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19232. * This stage will be fired no matter what
  19233. */
  19234. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19235. /**
  19236. * Called before opaque object are rendered.
  19237. * This stage will be fired only if there's 3D Opaque content to render
  19238. */
  19239. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19240. /**
  19241. * Called after the opaque objects are rendered and before the transparent ones
  19242. * This stage will be fired only if there's 3D transparent content to render
  19243. */
  19244. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19245. /**
  19246. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19247. * This stage will be fired no matter what
  19248. */
  19249. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19250. return RenderingGroupInfo;
  19251. }());
  19252. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19253. /**
  19254. * Represents a scene to be rendered by the engine.
  19255. * @see http://doc.babylonjs.com/page.php?p=21911
  19256. */
  19257. var Scene = /** @class */ (function () {
  19258. /**
  19259. * @constructor
  19260. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19261. */
  19262. function Scene(engine) {
  19263. // Members
  19264. this.autoClear = true;
  19265. this.autoClearDepthAndStencil = true;
  19266. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19267. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19268. this.forceWireframe = false;
  19269. this._forcePointsCloud = false;
  19270. this.forceShowBoundingBoxes = false;
  19271. this.animationsEnabled = true;
  19272. this.useConstantAnimationDeltaTime = false;
  19273. this.constantlyUpdateMeshUnderPointer = false;
  19274. this.hoverCursor = "pointer";
  19275. this.defaultCursor = "";
  19276. /**
  19277. * This is used to call preventDefault() on pointer down
  19278. * in order to block unwanted artifacts like system double clicks
  19279. */
  19280. this.preventDefaultOnPointerDown = true;
  19281. // Metadata
  19282. this.metadata = null;
  19283. /**
  19284. * An event triggered when the scene is disposed.
  19285. * @type {BABYLON.Observable}
  19286. */
  19287. this.onDisposeObservable = new BABYLON.Observable();
  19288. /**
  19289. * An event triggered before rendering the scene (right after animations and physics)
  19290. * @type {BABYLON.Observable}
  19291. */
  19292. this.onBeforeRenderObservable = new BABYLON.Observable();
  19293. /**
  19294. * An event triggered after rendering the scene
  19295. * @type {BABYLON.Observable}
  19296. */
  19297. this.onAfterRenderObservable = new BABYLON.Observable();
  19298. /**
  19299. * An event triggered before animating the scene
  19300. * @type {BABYLON.Observable}
  19301. */
  19302. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19303. /**
  19304. * An event triggered after animations processing
  19305. * @type {BABYLON.Observable}
  19306. */
  19307. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19308. /**
  19309. * An event triggered before draw calls are ready to be sent
  19310. * @type {BABYLON.Observable}
  19311. */
  19312. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19313. /**
  19314. * An event triggered after draw calls have been sent
  19315. * @type {BABYLON.Observable}
  19316. */
  19317. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19318. /**
  19319. * An event triggered when physic simulation is about to be run
  19320. * @type {BABYLON.Observable}
  19321. */
  19322. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19323. /**
  19324. * An event triggered when physic simulation has been done
  19325. * @type {BABYLON.Observable}
  19326. */
  19327. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19328. /**
  19329. * An event triggered when the scene is ready
  19330. * @type {BABYLON.Observable}
  19331. */
  19332. this.onReadyObservable = new BABYLON.Observable();
  19333. /**
  19334. * An event triggered before rendering a camera
  19335. * @type {BABYLON.Observable}
  19336. */
  19337. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19338. /**
  19339. * An event triggered after rendering a camera
  19340. * @type {BABYLON.Observable}
  19341. */
  19342. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19343. /**
  19344. * An event triggered when active meshes evaluation is about to start
  19345. * @type {BABYLON.Observable}
  19346. */
  19347. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19348. /**
  19349. * An event triggered when active meshes evaluation is done
  19350. * @type {BABYLON.Observable}
  19351. */
  19352. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19353. /**
  19354. * An event triggered when particles rendering is about to start
  19355. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19356. * @type {BABYLON.Observable}
  19357. */
  19358. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19359. /**
  19360. * An event triggered when particles rendering is done
  19361. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19362. * @type {BABYLON.Observable}
  19363. */
  19364. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19365. /**
  19366. * An event triggered when sprites rendering is about to start
  19367. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19368. * @type {BABYLON.Observable}
  19369. */
  19370. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19371. /**
  19372. * An event triggered when sprites rendering is done
  19373. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19374. * @type {BABYLON.Observable}
  19375. */
  19376. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19377. /**
  19378. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19379. * @type {BABYLON.Observable}
  19380. */
  19381. this.onDataLoadedObservable = new BABYLON.Observable();
  19382. /**
  19383. * An event triggered when a camera is created
  19384. * @type {BABYLON.Observable}
  19385. */
  19386. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19387. /**
  19388. * An event triggered when a camera is removed
  19389. * @type {BABYLON.Observable}
  19390. */
  19391. this.onCameraRemovedObservable = new BABYLON.Observable();
  19392. /**
  19393. * An event triggered when a light is created
  19394. * @type {BABYLON.Observable}
  19395. */
  19396. this.onNewLightAddedObservable = new BABYLON.Observable();
  19397. /**
  19398. * An event triggered when a light is removed
  19399. * @type {BABYLON.Observable}
  19400. */
  19401. this.onLightRemovedObservable = new BABYLON.Observable();
  19402. /**
  19403. * An event triggered when a geometry is created
  19404. * @type {BABYLON.Observable}
  19405. */
  19406. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19407. /**
  19408. * An event triggered when a geometry is removed
  19409. * @type {BABYLON.Observable}
  19410. */
  19411. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19412. /**
  19413. * An event triggered when a transform node is created
  19414. * @type {BABYLON.Observable}
  19415. */
  19416. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19417. /**
  19418. * An event triggered when a transform node is removed
  19419. * @type {BABYLON.Observable}
  19420. */
  19421. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19422. /**
  19423. * An event triggered when a mesh is created
  19424. * @type {BABYLON.Observable}
  19425. */
  19426. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19427. /**
  19428. * An event triggered when a mesh is removed
  19429. * @type {BABYLON.Observable}
  19430. */
  19431. this.onMeshRemovedObservable = new BABYLON.Observable();
  19432. /**
  19433. * An event triggered when render targets are about to be rendered
  19434. * Can happen multiple times per frame.
  19435. * @type {BABYLON.Observable}
  19436. */
  19437. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19438. /**
  19439. * An event triggered when render targets were rendered.
  19440. * Can happen multiple times per frame.
  19441. * @type {BABYLON.Observable}
  19442. */
  19443. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19444. /**
  19445. * An event triggered before calculating deterministic simulation step
  19446. * @type {BABYLON.Observable}
  19447. */
  19448. this.onBeforeStepObservable = new BABYLON.Observable();
  19449. /**
  19450. * An event triggered after calculating deterministic simulation step
  19451. * @type {BABYLON.Observable}
  19452. */
  19453. this.onAfterStepObservable = new BABYLON.Observable();
  19454. /**
  19455. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19456. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19457. * 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)
  19458. */
  19459. this.onRenderingGroupObservable = new BABYLON.Observable();
  19460. // Animations
  19461. this.animations = [];
  19462. /**
  19463. * 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).
  19464. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19465. */
  19466. this.onPrePointerObservable = new BABYLON.Observable();
  19467. /**
  19468. * Observable event triggered each time an input event is received from the rendering canvas
  19469. */
  19470. this.onPointerObservable = new BABYLON.Observable();
  19471. this._meshPickProceed = false;
  19472. this._currentPickResult = null;
  19473. this._previousPickResult = null;
  19474. this._totalPointersPressed = 0;
  19475. this._doubleClickOccured = false;
  19476. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19477. this.cameraToUseForPointers = null;
  19478. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19479. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19480. this._startingPointerTime = 0;
  19481. this._previousStartingPointerTime = 0;
  19482. // Deterministic lockstep
  19483. this._timeAccumulator = 0;
  19484. this._currentStepId = 0;
  19485. this._currentInternalStep = 0;
  19486. // Keyboard
  19487. /**
  19488. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19489. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19490. */
  19491. this.onPreKeyboardObservable = new BABYLON.Observable();
  19492. /**
  19493. * Observable event triggered each time an keyboard event is received from the hosting window
  19494. */
  19495. this.onKeyboardObservable = new BABYLON.Observable();
  19496. // Coordinate system
  19497. /**
  19498. * use right-handed coordinate system on this scene.
  19499. * @type {boolean}
  19500. */
  19501. this._useRightHandedSystem = false;
  19502. // Fog
  19503. this._fogEnabled = true;
  19504. this._fogMode = Scene.FOGMODE_NONE;
  19505. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19506. this.fogDensity = 0.1;
  19507. this.fogStart = 0;
  19508. this.fogEnd = 1000.0;
  19509. // Lights
  19510. /**
  19511. * is shadow enabled on this scene.
  19512. * @type {boolean}
  19513. */
  19514. this._shadowsEnabled = true;
  19515. /**
  19516. * is light enabled on this scene.
  19517. * @type {boolean}
  19518. */
  19519. this._lightsEnabled = true;
  19520. /**
  19521. * All of the lights added to this scene.
  19522. * @see BABYLON.Light
  19523. * @type {BABYLON.Light[]}
  19524. */
  19525. this.lights = new Array();
  19526. // Cameras
  19527. /** All of the cameras added to this scene. */
  19528. this.cameras = new Array();
  19529. /** All of the active cameras added to this scene. */
  19530. this.activeCameras = new Array();
  19531. // Meshes
  19532. /**
  19533. * All of the tranform nodes added to this scene.
  19534. * @see BABYLON.TransformNode
  19535. * @type {BABYLON.TransformNode[]}
  19536. */
  19537. this.transformNodes = new Array();
  19538. /**
  19539. * All of the (abstract) meshes added to this scene.
  19540. * @see BABYLON.AbstractMesh
  19541. * @type {BABYLON.AbstractMesh[]}
  19542. */
  19543. this.meshes = new Array();
  19544. /**
  19545. * All of the animation groups added to this scene.
  19546. * @see BABYLON.AnimationGroup
  19547. * @type {BABYLON.AnimationGroup[]}
  19548. */
  19549. this.animationGroups = new Array();
  19550. // Geometries
  19551. this._geometries = new Array();
  19552. this.materials = new Array();
  19553. this.multiMaterials = new Array();
  19554. // Textures
  19555. this._texturesEnabled = true;
  19556. this.textures = new Array();
  19557. // Particles
  19558. this.particlesEnabled = true;
  19559. this.particleSystems = new Array();
  19560. // Sprites
  19561. this.spritesEnabled = true;
  19562. this.spriteManagers = new Array();
  19563. // Layers
  19564. this.layers = new Array();
  19565. this.highlightLayers = new Array();
  19566. // Skeletons
  19567. this._skeletonsEnabled = true;
  19568. this.skeletons = new Array();
  19569. // Morph targets
  19570. this.morphTargetManagers = new Array();
  19571. // Lens flares
  19572. this.lensFlaresEnabled = true;
  19573. this.lensFlareSystems = new Array();
  19574. // Collisions
  19575. this.collisionsEnabled = true;
  19576. /** Defines the gravity applied to this scene */
  19577. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19578. // Postprocesses
  19579. this.postProcesses = new Array();
  19580. this.postProcessesEnabled = true;
  19581. // Customs render targets
  19582. this.renderTargetsEnabled = true;
  19583. this.dumpNextRenderTargets = false;
  19584. this.customRenderTargets = new Array();
  19585. // Imported meshes
  19586. this.importedMeshesFiles = new Array();
  19587. // Probes
  19588. this.probesEnabled = true;
  19589. this.reflectionProbes = new Array();
  19590. this._actionManagers = new Array();
  19591. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19592. // Procedural textures
  19593. this.proceduralTexturesEnabled = true;
  19594. this._proceduralTextures = new Array();
  19595. this.soundTracks = new Array();
  19596. this._audioEnabled = true;
  19597. this._headphone = false;
  19598. // Performance counters
  19599. this._totalVertices = new BABYLON.PerfCounter();
  19600. this._activeIndices = new BABYLON.PerfCounter();
  19601. this._activeParticles = new BABYLON.PerfCounter();
  19602. this._activeBones = new BABYLON.PerfCounter();
  19603. this._animationTime = 0;
  19604. this.animationTimeScale = 1;
  19605. this._renderId = 0;
  19606. this._executeWhenReadyTimeoutId = -1;
  19607. this._intermediateRendering = false;
  19608. this._viewUpdateFlag = -1;
  19609. this._projectionUpdateFlag = -1;
  19610. this._alternateViewUpdateFlag = -1;
  19611. this._alternateProjectionUpdateFlag = -1;
  19612. this._toBeDisposed = new BABYLON.SmartArray(256);
  19613. this._activeRequests = new Array();
  19614. this._pendingData = new Array();
  19615. this._isDisposed = false;
  19616. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19617. this._activeMeshes = new BABYLON.SmartArray(256);
  19618. this._processedMaterials = new BABYLON.SmartArray(256);
  19619. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19620. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19621. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19622. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19623. this._activeAnimatables = new Array();
  19624. this._transformMatrix = BABYLON.Matrix.Zero();
  19625. this._useAlternateCameraConfiguration = false;
  19626. this._alternateRendering = false;
  19627. this.requireLightSorting = false;
  19628. this._activeMeshesFrozen = false;
  19629. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19630. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19631. this._engine.scenes.push(this);
  19632. this._uid = null;
  19633. this._renderingManager = new BABYLON.RenderingManager(this);
  19634. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19635. if (BABYLON.OutlineRenderer) {
  19636. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19637. }
  19638. if (BABYLON.Tools.IsWindowObjectExist()) {
  19639. this.attachControl();
  19640. }
  19641. //simplification queue
  19642. if (BABYLON.SimplificationQueue) {
  19643. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19644. }
  19645. //collision coordinator initialization. For now legacy per default.
  19646. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19647. // Uniform Buffer
  19648. this._createUbo();
  19649. // Default Image processing definition.
  19650. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19651. }
  19652. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19653. /** The fog is deactivated */
  19654. get: function () {
  19655. return Scene._FOGMODE_NONE;
  19656. },
  19657. enumerable: true,
  19658. configurable: true
  19659. });
  19660. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19661. /** The fog density is following an exponential function */
  19662. get: function () {
  19663. return Scene._FOGMODE_EXP;
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19669. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19670. get: function () {
  19671. return Scene._FOGMODE_EXP2;
  19672. },
  19673. enumerable: true,
  19674. configurable: true
  19675. });
  19676. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19677. /** The fog density is following a linear function. */
  19678. get: function () {
  19679. return Scene._FOGMODE_LINEAR;
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19685. /**
  19686. * Texture used in all pbr material as the reflection texture.
  19687. * As in the majority of the scene they are the same (exception for multi room and so on),
  19688. * this is easier to reference from here than from all the materials.
  19689. */
  19690. get: function () {
  19691. return this._environmentTexture;
  19692. },
  19693. /**
  19694. * Texture used in all pbr material as the reflection texture.
  19695. * As in the majority of the scene they are the same (exception for multi room and so on),
  19696. * this is easier to set here than in all the materials.
  19697. */
  19698. set: function (value) {
  19699. if (this._environmentTexture === value) {
  19700. return;
  19701. }
  19702. this._environmentTexture = value;
  19703. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19704. },
  19705. enumerable: true,
  19706. configurable: true
  19707. });
  19708. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19709. /**
  19710. * Default image processing configuration used either in the rendering
  19711. * Forward main pass or through the imageProcessingPostProcess if present.
  19712. * As in the majority of the scene they are the same (exception for multi camera),
  19713. * this is easier to reference from here than from all the materials and post process.
  19714. *
  19715. * No setter as we it is a shared configuration, you can set the values instead.
  19716. */
  19717. get: function () {
  19718. return this._imageProcessingConfiguration;
  19719. },
  19720. enumerable: true,
  19721. configurable: true
  19722. });
  19723. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19724. get: function () {
  19725. return this._forcePointsCloud;
  19726. },
  19727. set: function (value) {
  19728. if (this._forcePointsCloud === value) {
  19729. return;
  19730. }
  19731. this._forcePointsCloud = value;
  19732. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(Scene.prototype, "onDispose", {
  19738. /** A function to be executed when this scene is disposed. */
  19739. set: function (callback) {
  19740. if (this._onDisposeObserver) {
  19741. this.onDisposeObservable.remove(this._onDisposeObserver);
  19742. }
  19743. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(Scene.prototype, "beforeRender", {
  19749. /** A function to be executed before rendering this scene */
  19750. set: function (callback) {
  19751. if (this._onBeforeRenderObserver) {
  19752. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19753. }
  19754. if (callback) {
  19755. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19756. }
  19757. },
  19758. enumerable: true,
  19759. configurable: true
  19760. });
  19761. Object.defineProperty(Scene.prototype, "afterRender", {
  19762. /** A function to be executed after rendering this scene */
  19763. set: function (callback) {
  19764. if (this._onAfterRenderObserver) {
  19765. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19766. }
  19767. if (callback) {
  19768. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19769. }
  19770. },
  19771. enumerable: true,
  19772. configurable: true
  19773. });
  19774. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19775. set: function (callback) {
  19776. if (this._onBeforeCameraRenderObserver) {
  19777. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19778. }
  19779. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19785. set: function (callback) {
  19786. if (this._onAfterCameraRenderObserver) {
  19787. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19788. }
  19789. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19790. },
  19791. enumerable: true,
  19792. configurable: true
  19793. });
  19794. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19795. get: function () {
  19796. if (!this._gamepadManager) {
  19797. this._gamepadManager = new BABYLON.GamepadManager(this);
  19798. }
  19799. return this._gamepadManager;
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19805. get: function () {
  19806. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19812. get: function () {
  19813. return this._useRightHandedSystem;
  19814. },
  19815. set: function (value) {
  19816. if (this._useRightHandedSystem === value) {
  19817. return;
  19818. }
  19819. this._useRightHandedSystem = value;
  19820. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Scene.prototype.setStepId = function (newStepId) {
  19826. this._currentStepId = newStepId;
  19827. };
  19828. ;
  19829. Scene.prototype.getStepId = function () {
  19830. return this._currentStepId;
  19831. };
  19832. ;
  19833. Scene.prototype.getInternalStep = function () {
  19834. return this._currentInternalStep;
  19835. };
  19836. ;
  19837. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19838. get: function () {
  19839. return this._fogEnabled;
  19840. },
  19841. /**
  19842. * is fog enabled on this scene.
  19843. */
  19844. set: function (value) {
  19845. if (this._fogEnabled === value) {
  19846. return;
  19847. }
  19848. this._fogEnabled = value;
  19849. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(Scene.prototype, "fogMode", {
  19855. get: function () {
  19856. return this._fogMode;
  19857. },
  19858. set: function (value) {
  19859. if (this._fogMode === value) {
  19860. return;
  19861. }
  19862. this._fogMode = value;
  19863. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19869. get: function () {
  19870. return this._shadowsEnabled;
  19871. },
  19872. set: function (value) {
  19873. if (this._shadowsEnabled === value) {
  19874. return;
  19875. }
  19876. this._shadowsEnabled = value;
  19877. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19878. },
  19879. enumerable: true,
  19880. configurable: true
  19881. });
  19882. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19883. get: function () {
  19884. return this._lightsEnabled;
  19885. },
  19886. set: function (value) {
  19887. if (this._lightsEnabled === value) {
  19888. return;
  19889. }
  19890. this._lightsEnabled = value;
  19891. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19892. },
  19893. enumerable: true,
  19894. configurable: true
  19895. });
  19896. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19897. /** The default material used on meshes when no material is affected */
  19898. get: function () {
  19899. if (!this._defaultMaterial) {
  19900. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19901. }
  19902. return this._defaultMaterial;
  19903. },
  19904. /** The default material used on meshes when no material is affected */
  19905. set: function (value) {
  19906. this._defaultMaterial = value;
  19907. },
  19908. enumerable: true,
  19909. configurable: true
  19910. });
  19911. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19912. get: function () {
  19913. return this._texturesEnabled;
  19914. },
  19915. set: function (value) {
  19916. if (this._texturesEnabled === value) {
  19917. return;
  19918. }
  19919. this._texturesEnabled = value;
  19920. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19921. },
  19922. enumerable: true,
  19923. configurable: true
  19924. });
  19925. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19926. get: function () {
  19927. return this._skeletonsEnabled;
  19928. },
  19929. set: function (value) {
  19930. if (this._skeletonsEnabled === value) {
  19931. return;
  19932. }
  19933. this._skeletonsEnabled = value;
  19934. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19940. get: function () {
  19941. if (!this._postProcessRenderPipelineManager) {
  19942. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19943. }
  19944. return this._postProcessRenderPipelineManager;
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19950. get: function () {
  19951. if (!this._mainSoundTrack) {
  19952. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19953. }
  19954. return this._mainSoundTrack;
  19955. },
  19956. enumerable: true,
  19957. configurable: true
  19958. });
  19959. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19960. get: function () {
  19961. return this._alternateRendering;
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19967. get: function () {
  19968. return this._frustumPlanes;
  19969. },
  19970. enumerable: true,
  19971. configurable: true
  19972. });
  19973. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  19974. /**
  19975. * Gets the current geometry buffer associated to the scene.
  19976. */
  19977. get: function () {
  19978. return this._geometryBufferRenderer;
  19979. },
  19980. /**
  19981. * Sets the current geometry buffer for the scene.
  19982. */
  19983. set: function (geometryBufferRenderer) {
  19984. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  19985. this._geometryBufferRenderer = geometryBufferRenderer;
  19986. }
  19987. },
  19988. enumerable: true,
  19989. configurable: true
  19990. });
  19991. Object.defineProperty(Scene.prototype, "debugLayer", {
  19992. // Properties
  19993. get: function () {
  19994. if (!this._debugLayer) {
  19995. this._debugLayer = new BABYLON.DebugLayer(this);
  19996. }
  19997. return this._debugLayer;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20003. get: function () {
  20004. return this._workerCollisions;
  20005. },
  20006. set: function (enabled) {
  20007. if (!BABYLON.CollisionCoordinatorLegacy) {
  20008. return;
  20009. }
  20010. enabled = (enabled && !!Worker);
  20011. this._workerCollisions = enabled;
  20012. if (this.collisionCoordinator) {
  20013. this.collisionCoordinator.destroy();
  20014. }
  20015. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20016. this.collisionCoordinator.init(this);
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20022. get: function () {
  20023. return this._selectionOctree;
  20024. },
  20025. enumerable: true,
  20026. configurable: true
  20027. });
  20028. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20029. /**
  20030. * The mesh that is currently under the pointer.
  20031. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20032. */
  20033. get: function () {
  20034. return this._pointerOverMesh;
  20035. },
  20036. enumerable: true,
  20037. configurable: true
  20038. });
  20039. Object.defineProperty(Scene.prototype, "pointerX", {
  20040. /**
  20041. * Current on-screen X position of the pointer
  20042. * @return {number} X position of the pointer
  20043. */
  20044. get: function () {
  20045. return this._pointerX;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(Scene.prototype, "pointerY", {
  20051. /**
  20052. * Current on-screen Y position of the pointer
  20053. * @return {number} Y position of the pointer
  20054. */
  20055. get: function () {
  20056. return this._pointerY;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. Scene.prototype.getCachedMaterial = function () {
  20062. return this._cachedMaterial;
  20063. };
  20064. Scene.prototype.getCachedEffect = function () {
  20065. return this._cachedEffect;
  20066. };
  20067. Scene.prototype.getCachedVisibility = function () {
  20068. return this._cachedVisibility;
  20069. };
  20070. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20071. if (visibility === void 0) { visibility = 1; }
  20072. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20073. };
  20074. Scene.prototype.getBoundingBoxRenderer = function () {
  20075. if (!this._boundingBoxRenderer) {
  20076. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20077. }
  20078. return this._boundingBoxRenderer;
  20079. };
  20080. Scene.prototype.getOutlineRenderer = function () {
  20081. return this._outlineRenderer;
  20082. };
  20083. Scene.prototype.getEngine = function () {
  20084. return this._engine;
  20085. };
  20086. Scene.prototype.getTotalVertices = function () {
  20087. return this._totalVertices.current;
  20088. };
  20089. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20090. get: function () {
  20091. return this._totalVertices;
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Scene.prototype.getActiveIndices = function () {
  20097. return this._activeIndices.current;
  20098. };
  20099. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20100. get: function () {
  20101. return this._activeIndices;
  20102. },
  20103. enumerable: true,
  20104. configurable: true
  20105. });
  20106. Scene.prototype.getActiveParticles = function () {
  20107. return this._activeParticles.current;
  20108. };
  20109. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20110. get: function () {
  20111. return this._activeParticles;
  20112. },
  20113. enumerable: true,
  20114. configurable: true
  20115. });
  20116. Scene.prototype.getActiveBones = function () {
  20117. return this._activeBones.current;
  20118. };
  20119. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20120. get: function () {
  20121. return this._activeBones;
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. // Stats
  20127. Scene.prototype.getInterFramePerfCounter = function () {
  20128. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20129. return 0;
  20130. };
  20131. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20132. get: function () {
  20133. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20134. return null;
  20135. },
  20136. enumerable: true,
  20137. configurable: true
  20138. });
  20139. Scene.prototype.getLastFrameDuration = function () {
  20140. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20141. return 0;
  20142. };
  20143. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20144. get: function () {
  20145. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20146. return null;
  20147. },
  20148. enumerable: true,
  20149. configurable: true
  20150. });
  20151. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20152. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20153. return 0;
  20154. };
  20155. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20156. get: function () {
  20157. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20158. return null;
  20159. },
  20160. enumerable: true,
  20161. configurable: true
  20162. });
  20163. Scene.prototype.getActiveMeshes = function () {
  20164. return this._activeMeshes;
  20165. };
  20166. Scene.prototype.getRenderTargetsDuration = function () {
  20167. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20168. return 0;
  20169. };
  20170. Scene.prototype.getRenderDuration = function () {
  20171. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20172. return 0;
  20173. };
  20174. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20175. get: function () {
  20176. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20177. return null;
  20178. },
  20179. enumerable: true,
  20180. configurable: true
  20181. });
  20182. Scene.prototype.getParticlesDuration = function () {
  20183. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20184. return 0;
  20185. };
  20186. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20187. get: function () {
  20188. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20189. return null;
  20190. },
  20191. enumerable: true,
  20192. configurable: true
  20193. });
  20194. Scene.prototype.getSpritesDuration = function () {
  20195. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20196. return 0;
  20197. };
  20198. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20199. get: function () {
  20200. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20201. return null;
  20202. },
  20203. enumerable: true,
  20204. configurable: true
  20205. });
  20206. Scene.prototype.getAnimationRatio = function () {
  20207. return this._animationRatio;
  20208. };
  20209. Scene.prototype.getRenderId = function () {
  20210. return this._renderId;
  20211. };
  20212. Scene.prototype.incrementRenderId = function () {
  20213. this._renderId++;
  20214. };
  20215. Scene.prototype._updatePointerPosition = function (evt) {
  20216. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20217. if (!canvasRect) {
  20218. return;
  20219. }
  20220. this._pointerX = evt.clientX - canvasRect.left;
  20221. this._pointerY = evt.clientY - canvasRect.top;
  20222. this._unTranslatedPointerX = this._pointerX;
  20223. this._unTranslatedPointerY = this._pointerY;
  20224. };
  20225. Scene.prototype._createUbo = function () {
  20226. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20227. this._sceneUbo.addUniform("viewProjection", 16);
  20228. this._sceneUbo.addUniform("view", 16);
  20229. };
  20230. Scene.prototype._createAlternateUbo = function () {
  20231. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20232. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20233. this._alternateSceneUbo.addUniform("view", 16);
  20234. };
  20235. // Pointers handling
  20236. /**
  20237. * Use this method to simulate a pointer move on a mesh
  20238. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20239. */
  20240. Scene.prototype.simulatePointerMove = function (pickResult) {
  20241. var evt = new PointerEvent("pointermove");
  20242. return this._processPointerMove(pickResult, evt);
  20243. };
  20244. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20245. var canvas = this._engine.getRenderingCanvas();
  20246. if (!canvas) {
  20247. return this;
  20248. }
  20249. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20250. this.setPointerOverSprite(null);
  20251. this.setPointerOverMesh(pickResult.pickedMesh);
  20252. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20253. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20254. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20255. }
  20256. else {
  20257. canvas.style.cursor = this.hoverCursor;
  20258. }
  20259. }
  20260. else {
  20261. canvas.style.cursor = this.defaultCursor;
  20262. }
  20263. }
  20264. else {
  20265. this.setPointerOverMesh(null);
  20266. // Sprites
  20267. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20268. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20269. this.setPointerOverSprite(pickResult.pickedSprite);
  20270. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20271. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20272. }
  20273. else {
  20274. canvas.style.cursor = this.hoverCursor;
  20275. }
  20276. }
  20277. else {
  20278. this.setPointerOverSprite(null);
  20279. // Restore pointer
  20280. canvas.style.cursor = this.defaultCursor;
  20281. }
  20282. }
  20283. if (pickResult) {
  20284. if (this.onPointerMove) {
  20285. this.onPointerMove(evt, pickResult);
  20286. }
  20287. if (this.onPointerObservable.hasObservers()) {
  20288. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20289. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20290. this.onPointerObservable.notifyObservers(pi, type);
  20291. }
  20292. }
  20293. return this;
  20294. };
  20295. /**
  20296. * Use this method to simulate a pointer down on a mesh
  20297. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20298. */
  20299. Scene.prototype.simulatePointerDown = function (pickResult) {
  20300. var evt = new PointerEvent("pointerdown");
  20301. return this._processPointerDown(pickResult, evt);
  20302. };
  20303. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20304. var _this = this;
  20305. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20306. this._pickedDownMesh = pickResult.pickedMesh;
  20307. var actionManager = pickResult.pickedMesh.actionManager;
  20308. if (actionManager) {
  20309. if (actionManager.hasPickTriggers) {
  20310. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20311. switch (evt.button) {
  20312. case 0:
  20313. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20314. break;
  20315. case 1:
  20316. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20317. break;
  20318. case 2:
  20319. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20320. break;
  20321. }
  20322. }
  20323. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20324. window.setTimeout(function () {
  20325. 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);
  20326. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20327. if (_this._totalPointersPressed !== 0 &&
  20328. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20329. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20330. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20331. _this._startingPointerTime = 0;
  20332. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20333. }
  20334. }
  20335. }, Scene.LongPressDelay);
  20336. }
  20337. }
  20338. }
  20339. if (pickResult) {
  20340. if (this.onPointerDown) {
  20341. this.onPointerDown(evt, pickResult);
  20342. }
  20343. if (this.onPointerObservable.hasObservers()) {
  20344. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20345. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20346. this.onPointerObservable.notifyObservers(pi, type);
  20347. }
  20348. }
  20349. return this;
  20350. };
  20351. /**
  20352. * Use this method to simulate a pointer up on a mesh
  20353. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20354. */
  20355. Scene.prototype.simulatePointerUp = function (pickResult) {
  20356. var evt = new PointerEvent("pointerup");
  20357. var clickInfo = new ClickInfo();
  20358. clickInfo.singleClick = true;
  20359. clickInfo.ignore = true;
  20360. return this._processPointerUp(pickResult, evt, clickInfo);
  20361. };
  20362. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20363. if (pickResult && pickResult && pickResult.pickedMesh) {
  20364. this._pickedUpMesh = pickResult.pickedMesh;
  20365. if (this._pickedDownMesh === this._pickedUpMesh) {
  20366. if (this.onPointerPick) {
  20367. this.onPointerPick(evt, pickResult);
  20368. }
  20369. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20370. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20371. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20372. this.onPointerObservable.notifyObservers(pi, type);
  20373. }
  20374. }
  20375. if (pickResult.pickedMesh.actionManager) {
  20376. if (clickInfo.ignore) {
  20377. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20378. }
  20379. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20380. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20381. }
  20382. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20383. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20384. }
  20385. }
  20386. }
  20387. if (this._pickedDownMesh &&
  20388. this._pickedDownMesh.actionManager &&
  20389. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20390. this._pickedDownMesh !== this._pickedUpMesh) {
  20391. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20392. }
  20393. if (this.onPointerUp) {
  20394. this.onPointerUp(evt, pickResult);
  20395. }
  20396. if (this.onPointerObservable.hasObservers()) {
  20397. if (!clickInfo.ignore) {
  20398. if (!clickInfo.hasSwiped) {
  20399. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20400. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20401. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20402. this.onPointerObservable.notifyObservers(pi, type);
  20403. }
  20404. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20405. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20406. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20407. this.onPointerObservable.notifyObservers(pi, type);
  20408. }
  20409. }
  20410. }
  20411. else {
  20412. var type = BABYLON.PointerEventTypes.POINTERUP;
  20413. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20414. this.onPointerObservable.notifyObservers(pi, type);
  20415. }
  20416. }
  20417. return this;
  20418. };
  20419. /**
  20420. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20421. * @param attachUp defines if you want to attach events to pointerup
  20422. * @param attachDown defines if you want to attach events to pointerdown
  20423. * @param attachMove defines if you want to attach events to pointermove
  20424. */
  20425. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20426. var _this = this;
  20427. if (attachUp === void 0) { attachUp = true; }
  20428. if (attachDown === void 0) { attachDown = true; }
  20429. if (attachMove === void 0) { attachMove = true; }
  20430. this._initActionManager = function (act, clickInfo) {
  20431. if (!_this._meshPickProceed) {
  20432. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20433. _this._currentPickResult = pickResult;
  20434. if (pickResult) {
  20435. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20436. }
  20437. _this._meshPickProceed = true;
  20438. }
  20439. return act;
  20440. };
  20441. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20442. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20443. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20444. btn !== _this._previousButtonPressed) {
  20445. _this._doubleClickOccured = false;
  20446. clickInfo.singleClick = true;
  20447. clickInfo.ignore = false;
  20448. cb(clickInfo, _this._currentPickResult);
  20449. }
  20450. };
  20451. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20452. var clickInfo = new ClickInfo();
  20453. _this._currentPickResult = null;
  20454. var act = null;
  20455. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20456. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20457. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20458. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20459. act = _this._initActionManager(act, clickInfo);
  20460. if (act)
  20461. checkPicking = act.hasPickTriggers;
  20462. }
  20463. if (checkPicking) {
  20464. var btn = evt.button;
  20465. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20466. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20467. if (!clickInfo.hasSwiped) {
  20468. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20469. if (!checkSingleClickImmediately) {
  20470. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20471. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20472. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20473. act = _this._initActionManager(act, clickInfo);
  20474. if (act)
  20475. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20476. }
  20477. }
  20478. if (checkSingleClickImmediately) {
  20479. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20480. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20481. btn !== _this._previousButtonPressed) {
  20482. clickInfo.singleClick = true;
  20483. cb(clickInfo, _this._currentPickResult);
  20484. }
  20485. }
  20486. else {
  20487. // wait that no double click has been raised during the double click delay
  20488. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20489. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20490. }
  20491. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20492. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20493. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20494. act = _this._initActionManager(act, clickInfo);
  20495. if (act)
  20496. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20497. }
  20498. if (checkDoubleClick) {
  20499. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20500. if (btn === _this._previousButtonPressed &&
  20501. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20502. !_this._doubleClickOccured) {
  20503. // pointer has not moved for 2 clicks, it's a double click
  20504. if (!clickInfo.hasSwiped &&
  20505. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20506. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20507. _this._previousStartingPointerTime = 0;
  20508. _this._doubleClickOccured = true;
  20509. clickInfo.doubleClick = true;
  20510. clickInfo.ignore = false;
  20511. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20512. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20513. }
  20514. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20515. cb(clickInfo, _this._currentPickResult);
  20516. }
  20517. else {
  20518. _this._doubleClickOccured = false;
  20519. _this._previousStartingPointerTime = _this._startingPointerTime;
  20520. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20521. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20522. _this._previousButtonPressed = btn;
  20523. if (Scene.ExclusiveDoubleClickMode) {
  20524. if (_this._previousDelayedSimpleClickTimeout) {
  20525. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20526. }
  20527. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20528. cb(clickInfo, _this._previousPickResult);
  20529. }
  20530. else {
  20531. cb(clickInfo, _this._currentPickResult);
  20532. }
  20533. }
  20534. }
  20535. else {
  20536. _this._doubleClickOccured = false;
  20537. _this._previousStartingPointerTime = _this._startingPointerTime;
  20538. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20539. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20540. _this._previousButtonPressed = btn;
  20541. }
  20542. }
  20543. }
  20544. }
  20545. clickInfo.ignore = true;
  20546. cb(clickInfo, _this._currentPickResult);
  20547. };
  20548. this._spritePredicate = function (sprite) {
  20549. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20550. };
  20551. this._onPointerMove = function (evt) {
  20552. _this._updatePointerPosition(evt);
  20553. // PreObservable support
  20554. if (_this.onPrePointerObservable.hasObservers()) {
  20555. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20556. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20557. _this.onPrePointerObservable.notifyObservers(pi, type);
  20558. if (pi.skipOnPointerObservable) {
  20559. return;
  20560. }
  20561. }
  20562. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20563. return;
  20564. }
  20565. if (!_this.pointerMovePredicate) {
  20566. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20567. }
  20568. // Meshes
  20569. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20570. _this._processPointerMove(pickResult, evt);
  20571. };
  20572. this._onPointerDown = function (evt) {
  20573. _this._totalPointersPressed++;
  20574. _this._pickedDownMesh = null;
  20575. _this._meshPickProceed = false;
  20576. _this._updatePointerPosition(evt);
  20577. if (_this.preventDefaultOnPointerDown && canvas) {
  20578. evt.preventDefault();
  20579. canvas.focus();
  20580. }
  20581. // PreObservable support
  20582. if (_this.onPrePointerObservable.hasObservers()) {
  20583. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20584. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20585. _this.onPrePointerObservable.notifyObservers(pi, type);
  20586. if (pi.skipOnPointerObservable) {
  20587. return;
  20588. }
  20589. }
  20590. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20591. return;
  20592. }
  20593. _this._startingPointerPosition.x = _this._pointerX;
  20594. _this._startingPointerPosition.y = _this._pointerY;
  20595. _this._startingPointerTime = new Date().getTime();
  20596. if (!_this.pointerDownPredicate) {
  20597. _this.pointerDownPredicate = function (mesh) {
  20598. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20599. };
  20600. }
  20601. // Meshes
  20602. _this._pickedDownMesh = null;
  20603. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20604. _this._processPointerDown(pickResult, evt);
  20605. // Sprites
  20606. _this._pickedDownSprite = null;
  20607. if (_this.spriteManagers.length > 0) {
  20608. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20609. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20610. if (pickResult.pickedSprite.actionManager) {
  20611. _this._pickedDownSprite = pickResult.pickedSprite;
  20612. switch (evt.button) {
  20613. case 0:
  20614. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20615. break;
  20616. case 1:
  20617. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20618. break;
  20619. case 2:
  20620. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20621. break;
  20622. }
  20623. if (pickResult.pickedSprite.actionManager) {
  20624. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20625. }
  20626. }
  20627. }
  20628. }
  20629. };
  20630. this._onPointerUp = function (evt) {
  20631. if (_this._totalPointersPressed === 0) {
  20632. return; // So we need to test it the pointer down was pressed before.
  20633. }
  20634. _this._totalPointersPressed--;
  20635. _this._pickedUpMesh = null;
  20636. _this._meshPickProceed = false;
  20637. _this._updatePointerPosition(evt);
  20638. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20639. // PreObservable support
  20640. if (_this.onPrePointerObservable.hasObservers()) {
  20641. if (!clickInfo.ignore) {
  20642. if (!clickInfo.hasSwiped) {
  20643. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20644. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20645. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20646. _this.onPrePointerObservable.notifyObservers(pi, type);
  20647. if (pi.skipOnPointerObservable) {
  20648. return;
  20649. }
  20650. }
  20651. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20652. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20653. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20654. _this.onPrePointerObservable.notifyObservers(pi, type);
  20655. if (pi.skipOnPointerObservable) {
  20656. return;
  20657. }
  20658. }
  20659. }
  20660. }
  20661. else {
  20662. var type = BABYLON.PointerEventTypes.POINTERUP;
  20663. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20664. _this.onPrePointerObservable.notifyObservers(pi, type);
  20665. if (pi.skipOnPointerObservable) {
  20666. return;
  20667. }
  20668. }
  20669. }
  20670. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20671. return;
  20672. }
  20673. if (!_this.pointerUpPredicate) {
  20674. _this.pointerUpPredicate = function (mesh) {
  20675. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20676. };
  20677. }
  20678. // Meshes
  20679. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20680. _this._initActionManager(null, clickInfo);
  20681. }
  20682. if (!pickResult) {
  20683. pickResult = _this._currentPickResult;
  20684. }
  20685. _this._processPointerUp(pickResult, evt, clickInfo);
  20686. // Sprites
  20687. if (_this.spriteManagers.length > 0) {
  20688. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20689. if (spritePickResult) {
  20690. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20691. if (spritePickResult.pickedSprite.actionManager) {
  20692. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20693. if (spritePickResult.pickedSprite.actionManager) {
  20694. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20695. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20696. }
  20697. }
  20698. }
  20699. }
  20700. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20701. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20702. }
  20703. }
  20704. }
  20705. _this._previousPickResult = _this._currentPickResult;
  20706. });
  20707. };
  20708. this._onKeyDown = function (evt) {
  20709. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20710. if (_this.onPreKeyboardObservable.hasObservers()) {
  20711. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20712. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20713. if (pi.skipOnPointerObservable) {
  20714. return;
  20715. }
  20716. }
  20717. if (_this.onKeyboardObservable.hasObservers()) {
  20718. var pi = new BABYLON.KeyboardInfo(type, evt);
  20719. _this.onKeyboardObservable.notifyObservers(pi, type);
  20720. }
  20721. if (_this.actionManager) {
  20722. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20723. }
  20724. };
  20725. this._onKeyUp = function (evt) {
  20726. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20727. if (_this.onPreKeyboardObservable.hasObservers()) {
  20728. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20729. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20730. if (pi.skipOnPointerObservable) {
  20731. return;
  20732. }
  20733. }
  20734. if (_this.onKeyboardObservable.hasObservers()) {
  20735. var pi = new BABYLON.KeyboardInfo(type, evt);
  20736. _this.onKeyboardObservable.notifyObservers(pi, type);
  20737. }
  20738. if (_this.actionManager) {
  20739. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20740. }
  20741. };
  20742. var engine = this.getEngine();
  20743. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20744. if (!canvas) {
  20745. return;
  20746. }
  20747. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20748. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20749. });
  20750. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20751. if (!canvas) {
  20752. return;
  20753. }
  20754. canvas.removeEventListener("keydown", _this._onKeyDown);
  20755. canvas.removeEventListener("keyup", _this._onKeyUp);
  20756. });
  20757. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20758. var canvas = this._engine.getRenderingCanvas();
  20759. if (!canvas) {
  20760. return;
  20761. }
  20762. if (attachMove) {
  20763. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20764. // Wheel
  20765. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20766. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20767. }
  20768. if (attachDown) {
  20769. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20770. }
  20771. if (attachUp) {
  20772. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20773. }
  20774. canvas.tabIndex = 1;
  20775. };
  20776. Scene.prototype.detachControl = function () {
  20777. var engine = this.getEngine();
  20778. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20779. var canvas = engine.getRenderingCanvas();
  20780. if (!canvas) {
  20781. return;
  20782. }
  20783. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20784. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20785. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20786. if (this._onCanvasBlurObserver) {
  20787. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20788. }
  20789. if (this._onCanvasFocusObserver) {
  20790. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20791. }
  20792. // Wheel
  20793. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20794. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20795. // Keyboard
  20796. canvas.removeEventListener("keydown", this._onKeyDown);
  20797. canvas.removeEventListener("keyup", this._onKeyUp);
  20798. // Observables
  20799. this.onKeyboardObservable.clear();
  20800. this.onPreKeyboardObservable.clear();
  20801. this.onPointerObservable.clear();
  20802. this.onPrePointerObservable.clear();
  20803. };
  20804. /**
  20805. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20806. * Delay loaded resources are not taking in account
  20807. * @return true if all required resources are ready
  20808. */
  20809. Scene.prototype.isReady = function () {
  20810. if (this._isDisposed) {
  20811. return false;
  20812. }
  20813. if (this._pendingData.length > 0) {
  20814. return false;
  20815. }
  20816. var index;
  20817. var engine = this.getEngine();
  20818. // Geometries
  20819. for (index = 0; index < this._geometries.length; index++) {
  20820. var geometry = this._geometries[index];
  20821. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20822. return false;
  20823. }
  20824. }
  20825. // Meshes
  20826. for (index = 0; index < this.meshes.length; index++) {
  20827. var mesh = this.meshes[index];
  20828. if (!mesh.isEnabled()) {
  20829. continue;
  20830. }
  20831. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20832. continue;
  20833. }
  20834. if (!mesh.isReady()) {
  20835. return false;
  20836. }
  20837. // Highlight layers
  20838. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20839. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20840. var layer = _a[_i];
  20841. if (!layer.hasMesh(mesh)) {
  20842. continue;
  20843. }
  20844. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20845. var subMesh = _c[_b];
  20846. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20847. return false;
  20848. }
  20849. }
  20850. }
  20851. }
  20852. return true;
  20853. };
  20854. Scene.prototype.resetCachedMaterial = function () {
  20855. this._cachedMaterial = null;
  20856. this._cachedEffect = null;
  20857. this._cachedVisibility = null;
  20858. };
  20859. Scene.prototype.registerBeforeRender = function (func) {
  20860. this.onBeforeRenderObservable.add(func);
  20861. };
  20862. Scene.prototype.unregisterBeforeRender = function (func) {
  20863. this.onBeforeRenderObservable.removeCallback(func);
  20864. };
  20865. Scene.prototype.registerAfterRender = function (func) {
  20866. this.onAfterRenderObservable.add(func);
  20867. };
  20868. Scene.prototype.unregisterAfterRender = function (func) {
  20869. this.onAfterRenderObservable.removeCallback(func);
  20870. };
  20871. Scene.prototype._executeOnceBeforeRender = function (func) {
  20872. var _this = this;
  20873. var execFunc = function () {
  20874. func();
  20875. setTimeout(function () {
  20876. _this.unregisterBeforeRender(execFunc);
  20877. });
  20878. };
  20879. this.registerBeforeRender(execFunc);
  20880. };
  20881. /**
  20882. * The provided function will run before render once and will be disposed afterwards.
  20883. * A timeout delay can be provided so that the function will be executed in N ms.
  20884. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20885. * @param func The function to be executed.
  20886. * @param timeout optional delay in ms
  20887. */
  20888. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20889. var _this = this;
  20890. if (timeout !== undefined) {
  20891. setTimeout(function () {
  20892. _this._executeOnceBeforeRender(func);
  20893. }, timeout);
  20894. }
  20895. else {
  20896. this._executeOnceBeforeRender(func);
  20897. }
  20898. };
  20899. Scene.prototype._addPendingData = function (data) {
  20900. this._pendingData.push(data);
  20901. };
  20902. Scene.prototype._removePendingData = function (data) {
  20903. var wasLoading = this.isLoading;
  20904. var index = this._pendingData.indexOf(data);
  20905. if (index !== -1) {
  20906. this._pendingData.splice(index, 1);
  20907. }
  20908. if (wasLoading && !this.isLoading) {
  20909. this.onDataLoadedObservable.notifyObservers(this);
  20910. }
  20911. };
  20912. Scene.prototype.getWaitingItemsCount = function () {
  20913. return this._pendingData.length;
  20914. };
  20915. Object.defineProperty(Scene.prototype, "isLoading", {
  20916. get: function () {
  20917. return this._pendingData.length > 0;
  20918. },
  20919. enumerable: true,
  20920. configurable: true
  20921. });
  20922. /**
  20923. * Registers a function to be executed when the scene is ready.
  20924. * @param {Function} func - the function to be executed.
  20925. */
  20926. Scene.prototype.executeWhenReady = function (func) {
  20927. var _this = this;
  20928. this.onReadyObservable.add(func);
  20929. if (this._executeWhenReadyTimeoutId !== -1) {
  20930. return;
  20931. }
  20932. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20933. _this._checkIsReady();
  20934. }, 150);
  20935. };
  20936. Scene.prototype._checkIsReady = function () {
  20937. var _this = this;
  20938. if (this.isReady()) {
  20939. this.onReadyObservable.notifyObservers(this);
  20940. this.onReadyObservable.clear();
  20941. this._executeWhenReadyTimeoutId = -1;
  20942. return;
  20943. }
  20944. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20945. _this._checkIsReady();
  20946. }, 150);
  20947. };
  20948. // Animations
  20949. /**
  20950. * Will start the animation sequence of a given target
  20951. * @param target - the target
  20952. * @param {number} from - from which frame should animation start
  20953. * @param {number} to - till which frame should animation run.
  20954. * @param {boolean} [loop] - should the animation loop
  20955. * @param {number} [speedRatio] - the speed in which to run the animation
  20956. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20957. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20958. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20959. * See BABYLON.Animatable
  20960. */
  20961. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20962. if (speedRatio === void 0) { speedRatio = 1.0; }
  20963. if (from > to && speedRatio > 0) {
  20964. speedRatio *= -1;
  20965. }
  20966. this.stopAnimation(target);
  20967. if (!animatable) {
  20968. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20969. }
  20970. // Local animations
  20971. if (target.animations) {
  20972. animatable.appendAnimations(target, target.animations);
  20973. }
  20974. // Children animations
  20975. if (target.getAnimatables) {
  20976. var animatables = target.getAnimatables();
  20977. for (var index = 0; index < animatables.length; index++) {
  20978. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20979. }
  20980. }
  20981. animatable.reset();
  20982. return animatable;
  20983. };
  20984. /**
  20985. * Begin a new animation on a given node
  20986. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20987. * @param {BABYLON.Animation[]} defines the list of animations to start
  20988. * @param {number} from defines the initial value
  20989. * @param {number} to defines the final value
  20990. * @param {boolean} loop defines if you want animation to loop (off by default)
  20991. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20992. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20993. * @returns the list of created animatables
  20994. */
  20995. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20996. if (speedRatio === undefined) {
  20997. speedRatio = 1.0;
  20998. }
  20999. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21000. return animatable;
  21001. };
  21002. /**
  21003. * Begin a new animation on a given node and its hierarchy
  21004. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21005. * @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.
  21006. * @param {BABYLON.Animation[]} defines the list of animations to start
  21007. * @param {number} from defines the initial value
  21008. * @param {number} to defines the final value
  21009. * @param {boolean} loop defines if you want animation to loop (off by default)
  21010. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21011. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21012. * @returns the list of animatables created for all nodes
  21013. */
  21014. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21015. var children = target.getDescendants(directDescendantsOnly);
  21016. var result = [];
  21017. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21018. var child = children_1[_i];
  21019. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21020. }
  21021. return result;
  21022. };
  21023. Scene.prototype.getAnimatableByTarget = function (target) {
  21024. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21025. if (this._activeAnimatables[index].target === target) {
  21026. return this._activeAnimatables[index];
  21027. }
  21028. }
  21029. return null;
  21030. };
  21031. Object.defineProperty(Scene.prototype, "animatables", {
  21032. get: function () {
  21033. return this._activeAnimatables;
  21034. },
  21035. enumerable: true,
  21036. configurable: true
  21037. });
  21038. /**
  21039. * Will stop the animation of the given target
  21040. * @param target - the target
  21041. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21042. * @see beginAnimation
  21043. */
  21044. Scene.prototype.stopAnimation = function (target, animationName) {
  21045. var animatable = this.getAnimatableByTarget(target);
  21046. if (animatable) {
  21047. animatable.stop(animationName);
  21048. }
  21049. };
  21050. /**
  21051. * Stops and removes all animations that have been applied to the scene
  21052. */
  21053. Scene.prototype.stopAllAnimations = function () {
  21054. if (this._activeAnimatables) {
  21055. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21056. this._activeAnimatables[i].stop();
  21057. }
  21058. this._activeAnimatables = [];
  21059. }
  21060. };
  21061. Scene.prototype._animate = function () {
  21062. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21063. return;
  21064. }
  21065. // Getting time
  21066. var now = BABYLON.Tools.Now;
  21067. if (!this._animationTimeLast) {
  21068. if (this._pendingData.length > 0) {
  21069. return;
  21070. }
  21071. this._animationTimeLast = now;
  21072. }
  21073. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21074. this._animationTime += deltaTime;
  21075. this._animationTimeLast = now;
  21076. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21077. this._activeAnimatables[index]._animate(this._animationTime);
  21078. }
  21079. };
  21080. // Matrix
  21081. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21082. this._useAlternateCameraConfiguration = active;
  21083. };
  21084. Scene.prototype.getViewMatrix = function () {
  21085. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21086. };
  21087. Scene.prototype.getProjectionMatrix = function () {
  21088. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21089. };
  21090. Scene.prototype.getTransformMatrix = function () {
  21091. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21092. };
  21093. Scene.prototype.setTransformMatrix = function (view, projection) {
  21094. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21095. return;
  21096. }
  21097. this._viewUpdateFlag = view.updateFlag;
  21098. this._projectionUpdateFlag = projection.updateFlag;
  21099. this._viewMatrix = view;
  21100. this._projectionMatrix = projection;
  21101. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21102. // Update frustum
  21103. if (!this._frustumPlanes) {
  21104. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21105. }
  21106. else {
  21107. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21108. }
  21109. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21110. var otherCamera = this.activeCamera._alternateCamera;
  21111. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21112. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21113. }
  21114. if (this._sceneUbo.useUbo) {
  21115. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21116. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21117. this._sceneUbo.update();
  21118. }
  21119. };
  21120. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21121. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21122. return;
  21123. }
  21124. this._alternateViewUpdateFlag = view.updateFlag;
  21125. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21126. this._alternateViewMatrix = view;
  21127. this._alternateProjectionMatrix = projection;
  21128. if (!this._alternateTransformMatrix) {
  21129. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21130. }
  21131. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21132. if (!this._alternateSceneUbo) {
  21133. this._createAlternateUbo();
  21134. }
  21135. if (this._alternateSceneUbo.useUbo) {
  21136. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21137. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21138. this._alternateSceneUbo.update();
  21139. }
  21140. };
  21141. Scene.prototype.getSceneUniformBuffer = function () {
  21142. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21143. };
  21144. // Methods
  21145. Scene.prototype.getUniqueId = function () {
  21146. var result = Scene._uniqueIdCounter;
  21147. Scene._uniqueIdCounter++;
  21148. return result;
  21149. };
  21150. Scene.prototype.addMesh = function (newMesh) {
  21151. this.meshes.push(newMesh);
  21152. //notify the collision coordinator
  21153. if (this.collisionCoordinator) {
  21154. this.collisionCoordinator.onMeshAdded(newMesh);
  21155. }
  21156. newMesh._resyncLightSources();
  21157. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21158. };
  21159. Scene.prototype.removeMesh = function (toRemove) {
  21160. var index = this.meshes.indexOf(toRemove);
  21161. if (index !== -1) {
  21162. // Remove from the scene if mesh found
  21163. this.meshes.splice(index, 1);
  21164. }
  21165. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21166. return index;
  21167. };
  21168. Scene.prototype.addTransformNode = function (newTransformNode) {
  21169. this.transformNodes.push(newTransformNode);
  21170. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21171. };
  21172. Scene.prototype.removeTransformNode = function (toRemove) {
  21173. var index = this.transformNodes.indexOf(toRemove);
  21174. if (index !== -1) {
  21175. // Remove from the scene if found
  21176. this.transformNodes.splice(index, 1);
  21177. }
  21178. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21179. return index;
  21180. };
  21181. Scene.prototype.removeSkeleton = function (toRemove) {
  21182. var index = this.skeletons.indexOf(toRemove);
  21183. if (index !== -1) {
  21184. // Remove from the scene if found
  21185. this.skeletons.splice(index, 1);
  21186. }
  21187. return index;
  21188. };
  21189. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21190. var index = this.morphTargetManagers.indexOf(toRemove);
  21191. if (index !== -1) {
  21192. // Remove from the scene if found
  21193. this.morphTargetManagers.splice(index, 1);
  21194. }
  21195. return index;
  21196. };
  21197. Scene.prototype.removeLight = function (toRemove) {
  21198. var index = this.lights.indexOf(toRemove);
  21199. if (index !== -1) {
  21200. // Remove from meshes
  21201. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21202. var mesh = _a[_i];
  21203. mesh._removeLightSource(toRemove);
  21204. }
  21205. // Remove from the scene if mesh found
  21206. this.lights.splice(index, 1);
  21207. this.sortLightsByPriority();
  21208. }
  21209. this.onLightRemovedObservable.notifyObservers(toRemove);
  21210. return index;
  21211. };
  21212. Scene.prototype.removeCamera = function (toRemove) {
  21213. var index = this.cameras.indexOf(toRemove);
  21214. if (index !== -1) {
  21215. // Remove from the scene if mesh found
  21216. this.cameras.splice(index, 1);
  21217. }
  21218. // Remove from activeCameras
  21219. var index2 = this.activeCameras.indexOf(toRemove);
  21220. if (index2 !== -1) {
  21221. // Remove from the scene if mesh found
  21222. this.activeCameras.splice(index2, 1);
  21223. }
  21224. // Reset the activeCamera
  21225. if (this.activeCamera === toRemove) {
  21226. if (this.cameras.length > 0) {
  21227. this.activeCamera = this.cameras[0];
  21228. }
  21229. else {
  21230. this.activeCamera = null;
  21231. }
  21232. }
  21233. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21234. return index;
  21235. };
  21236. Scene.prototype.removeParticleSystem = function (toRemove) {
  21237. var index = this.particleSystems.indexOf(toRemove);
  21238. if (index !== -1) {
  21239. this.particleSystems.splice(index, 1);
  21240. }
  21241. return index;
  21242. };
  21243. ;
  21244. Scene.prototype.removeAnimation = function (toRemove) {
  21245. var index = this.animations.indexOf(toRemove);
  21246. if (index !== -1) {
  21247. this.animations.splice(index, 1);
  21248. }
  21249. return index;
  21250. };
  21251. ;
  21252. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21253. var index = this.multiMaterials.indexOf(toRemove);
  21254. if (index !== -1) {
  21255. this.multiMaterials.splice(index, 1);
  21256. }
  21257. return index;
  21258. };
  21259. ;
  21260. Scene.prototype.removeMaterial = function (toRemove) {
  21261. var index = this.materials.indexOf(toRemove);
  21262. if (index !== -1) {
  21263. this.materials.splice(index, 1);
  21264. }
  21265. return index;
  21266. };
  21267. ;
  21268. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21269. var index = this.lensFlareSystems.indexOf(toRemove);
  21270. if (index !== -1) {
  21271. this.lensFlareSystems.splice(index, 1);
  21272. }
  21273. return index;
  21274. };
  21275. ;
  21276. Scene.prototype.removeActionManager = function (toRemove) {
  21277. var index = this._actionManagers.indexOf(toRemove);
  21278. if (index !== -1) {
  21279. this._actionManagers.splice(index, 1);
  21280. }
  21281. return index;
  21282. };
  21283. ;
  21284. Scene.prototype.addLight = function (newLight) {
  21285. this.lights.push(newLight);
  21286. this.sortLightsByPriority();
  21287. // Add light to all meshes (To support if the light is removed and then readded)
  21288. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21289. var mesh = _a[_i];
  21290. if (mesh._lightSources.indexOf(newLight) === -1) {
  21291. mesh._lightSources.push(newLight);
  21292. mesh._resyncLightSources();
  21293. }
  21294. }
  21295. this.onNewLightAddedObservable.notifyObservers(newLight);
  21296. };
  21297. Scene.prototype.sortLightsByPriority = function () {
  21298. if (this.requireLightSorting) {
  21299. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21300. }
  21301. };
  21302. Scene.prototype.addCamera = function (newCamera) {
  21303. this.cameras.push(newCamera);
  21304. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21305. };
  21306. Scene.prototype.addSkeleton = function (newSkeleton) {
  21307. this.skeletons.push(newSkeleton);
  21308. };
  21309. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21310. this.particleSystems.push(newParticleSystem);
  21311. };
  21312. Scene.prototype.addAnimation = function (newAnimation) {
  21313. this.animations.push(newAnimation);
  21314. };
  21315. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21316. this.multiMaterials.push(newMultiMaterial);
  21317. };
  21318. Scene.prototype.addMaterial = function (newMaterial) {
  21319. this.materials.push(newMaterial);
  21320. };
  21321. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21322. this.morphTargetManagers.push(newMorphTargetManager);
  21323. };
  21324. Scene.prototype.addGeometry = function (newGeometrie) {
  21325. this._geometries.push(newGeometrie);
  21326. };
  21327. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21328. this.lensFlareSystems.push(newLensFlareSystem);
  21329. };
  21330. Scene.prototype.addActionManager = function (newActionManager) {
  21331. this._actionManagers.push(newActionManager);
  21332. };
  21333. /**
  21334. * Switch active camera
  21335. * @param {Camera} newCamera - new active camera
  21336. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21337. */
  21338. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21339. if (attachControl === void 0) { attachControl = true; }
  21340. var canvas = this._engine.getRenderingCanvas();
  21341. if (!canvas) {
  21342. return;
  21343. }
  21344. if (this.activeCamera) {
  21345. this.activeCamera.detachControl(canvas);
  21346. }
  21347. this.activeCamera = newCamera;
  21348. if (attachControl) {
  21349. newCamera.attachControl(canvas);
  21350. }
  21351. };
  21352. /**
  21353. * sets the active camera of the scene using its ID
  21354. * @param {string} id - the camera's ID
  21355. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21356. * @see activeCamera
  21357. */
  21358. Scene.prototype.setActiveCameraByID = function (id) {
  21359. var camera = this.getCameraByID(id);
  21360. if (camera) {
  21361. this.activeCamera = camera;
  21362. return camera;
  21363. }
  21364. return null;
  21365. };
  21366. /**
  21367. * sets the active camera of the scene using its name
  21368. * @param {string} name - the camera's name
  21369. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21370. * @see activeCamera
  21371. */
  21372. Scene.prototype.setActiveCameraByName = function (name) {
  21373. var camera = this.getCameraByName(name);
  21374. if (camera) {
  21375. this.activeCamera = camera;
  21376. return camera;
  21377. }
  21378. return null;
  21379. };
  21380. /**
  21381. * get an animation group using its name
  21382. * @param {string} the material's name
  21383. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21384. */
  21385. Scene.prototype.getAnimationGroupByName = function (name) {
  21386. for (var index = 0; index < this.animationGroups.length; index++) {
  21387. if (this.animationGroups[index].name === name) {
  21388. return this.animationGroups[index];
  21389. }
  21390. }
  21391. return null;
  21392. };
  21393. /**
  21394. * get a material using its id
  21395. * @param {string} the material's ID
  21396. * @return {BABYLON.Material|null} the material or null if none found.
  21397. */
  21398. Scene.prototype.getMaterialByID = function (id) {
  21399. for (var index = 0; index < this.materials.length; index++) {
  21400. if (this.materials[index].id === id) {
  21401. return this.materials[index];
  21402. }
  21403. }
  21404. return null;
  21405. };
  21406. /**
  21407. * get a material using its name
  21408. * @param {string} the material's name
  21409. * @return {BABYLON.Material|null} the material or null if none found.
  21410. */
  21411. Scene.prototype.getMaterialByName = function (name) {
  21412. for (var index = 0; index < this.materials.length; index++) {
  21413. if (this.materials[index].name === name) {
  21414. return this.materials[index];
  21415. }
  21416. }
  21417. return null;
  21418. };
  21419. Scene.prototype.getLensFlareSystemByName = function (name) {
  21420. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21421. if (this.lensFlareSystems[index].name === name) {
  21422. return this.lensFlareSystems[index];
  21423. }
  21424. }
  21425. return null;
  21426. };
  21427. Scene.prototype.getLensFlareSystemByID = function (id) {
  21428. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21429. if (this.lensFlareSystems[index].id === id) {
  21430. return this.lensFlareSystems[index];
  21431. }
  21432. }
  21433. return null;
  21434. };
  21435. Scene.prototype.getCameraByID = function (id) {
  21436. for (var index = 0; index < this.cameras.length; index++) {
  21437. if (this.cameras[index].id === id) {
  21438. return this.cameras[index];
  21439. }
  21440. }
  21441. return null;
  21442. };
  21443. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21444. for (var index = 0; index < this.cameras.length; index++) {
  21445. if (this.cameras[index].uniqueId === uniqueId) {
  21446. return this.cameras[index];
  21447. }
  21448. }
  21449. return null;
  21450. };
  21451. /**
  21452. * get a camera using its name
  21453. * @param {string} the camera's name
  21454. * @return {BABYLON.Camera|null} the camera or null if none found.
  21455. */
  21456. Scene.prototype.getCameraByName = function (name) {
  21457. for (var index = 0; index < this.cameras.length; index++) {
  21458. if (this.cameras[index].name === name) {
  21459. return this.cameras[index];
  21460. }
  21461. }
  21462. return null;
  21463. };
  21464. /**
  21465. * get a bone using its id
  21466. * @param {string} the bone's id
  21467. * @return {BABYLON.Bone|null} the bone or null if not found
  21468. */
  21469. Scene.prototype.getBoneByID = function (id) {
  21470. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21471. var skeleton = this.skeletons[skeletonIndex];
  21472. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21473. if (skeleton.bones[boneIndex].id === id) {
  21474. return skeleton.bones[boneIndex];
  21475. }
  21476. }
  21477. }
  21478. return null;
  21479. };
  21480. /**
  21481. * get a bone using its id
  21482. * @param {string} the bone's name
  21483. * @return {BABYLON.Bone|null} the bone or null if not found
  21484. */
  21485. Scene.prototype.getBoneByName = function (name) {
  21486. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21487. var skeleton = this.skeletons[skeletonIndex];
  21488. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21489. if (skeleton.bones[boneIndex].name === name) {
  21490. return skeleton.bones[boneIndex];
  21491. }
  21492. }
  21493. }
  21494. return null;
  21495. };
  21496. /**
  21497. * get a light node using its name
  21498. * @param {string} the light's name
  21499. * @return {BABYLON.Light|null} the light or null if none found.
  21500. */
  21501. Scene.prototype.getLightByName = function (name) {
  21502. for (var index = 0; index < this.lights.length; index++) {
  21503. if (this.lights[index].name === name) {
  21504. return this.lights[index];
  21505. }
  21506. }
  21507. return null;
  21508. };
  21509. /**
  21510. * get a light node using its ID
  21511. * @param {string} the light's id
  21512. * @return {BABYLON.Light|null} the light or null if none found.
  21513. */
  21514. Scene.prototype.getLightByID = function (id) {
  21515. for (var index = 0; index < this.lights.length; index++) {
  21516. if (this.lights[index].id === id) {
  21517. return this.lights[index];
  21518. }
  21519. }
  21520. return null;
  21521. };
  21522. /**
  21523. * get a light node using its scene-generated unique ID
  21524. * @param {number} the light's unique id
  21525. * @return {BABYLON.Light|null} the light or null if none found.
  21526. */
  21527. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21528. for (var index = 0; index < this.lights.length; index++) {
  21529. if (this.lights[index].uniqueId === uniqueId) {
  21530. return this.lights[index];
  21531. }
  21532. }
  21533. return null;
  21534. };
  21535. /**
  21536. * get a particle system by id
  21537. * @param id {number} the particle system id
  21538. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21539. */
  21540. Scene.prototype.getParticleSystemByID = function (id) {
  21541. for (var index = 0; index < this.particleSystems.length; index++) {
  21542. if (this.particleSystems[index].id === id) {
  21543. return this.particleSystems[index];
  21544. }
  21545. }
  21546. return null;
  21547. };
  21548. /**
  21549. * get a geometry using its ID
  21550. * @param {string} the geometry's id
  21551. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21552. */
  21553. Scene.prototype.getGeometryByID = function (id) {
  21554. for (var index = 0; index < this._geometries.length; index++) {
  21555. if (this._geometries[index].id === id) {
  21556. return this._geometries[index];
  21557. }
  21558. }
  21559. return null;
  21560. };
  21561. /**
  21562. * add a new geometry to this scene.
  21563. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21564. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21565. * @return {boolean} was the geometry added or not
  21566. */
  21567. Scene.prototype.pushGeometry = function (geometry, force) {
  21568. if (!force && this.getGeometryByID(geometry.id)) {
  21569. return false;
  21570. }
  21571. this._geometries.push(geometry);
  21572. //notify the collision coordinator
  21573. if (this.collisionCoordinator) {
  21574. this.collisionCoordinator.onGeometryAdded(geometry);
  21575. }
  21576. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21577. return true;
  21578. };
  21579. /**
  21580. * Removes an existing geometry
  21581. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21582. * @return {boolean} was the geometry removed or not
  21583. */
  21584. Scene.prototype.removeGeometry = function (geometry) {
  21585. var index = this._geometries.indexOf(geometry);
  21586. if (index > -1) {
  21587. this._geometries.splice(index, 1);
  21588. //notify the collision coordinator
  21589. if (this.collisionCoordinator) {
  21590. this.collisionCoordinator.onGeometryDeleted(geometry);
  21591. }
  21592. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21593. return true;
  21594. }
  21595. return false;
  21596. };
  21597. Scene.prototype.getGeometries = function () {
  21598. return this._geometries;
  21599. };
  21600. /**
  21601. * Get the first added mesh found of a given ID
  21602. * @param {string} id - the id to search for
  21603. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21604. */
  21605. Scene.prototype.getMeshByID = function (id) {
  21606. for (var index = 0; index < this.meshes.length; index++) {
  21607. if (this.meshes[index].id === id) {
  21608. return this.meshes[index];
  21609. }
  21610. }
  21611. return null;
  21612. };
  21613. Scene.prototype.getMeshesByID = function (id) {
  21614. return this.meshes.filter(function (m) {
  21615. return m.id === id;
  21616. });
  21617. };
  21618. /**
  21619. * Get the first added transform node found of a given ID
  21620. * @param {string} id - the id to search for
  21621. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21622. */
  21623. Scene.prototype.getTransformNodeByID = function (id) {
  21624. for (var index = 0; index < this.transformNodes.length; index++) {
  21625. if (this.transformNodes[index].id === id) {
  21626. return this.transformNodes[index];
  21627. }
  21628. }
  21629. return null;
  21630. };
  21631. Scene.prototype.getTransformNodesByID = function (id) {
  21632. return this.transformNodes.filter(function (m) {
  21633. return m.id === id;
  21634. });
  21635. };
  21636. /**
  21637. * Get a mesh with its auto-generated unique id
  21638. * @param {number} uniqueId - the unique id to search for
  21639. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21640. */
  21641. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21642. for (var index = 0; index < this.meshes.length; index++) {
  21643. if (this.meshes[index].uniqueId === uniqueId) {
  21644. return this.meshes[index];
  21645. }
  21646. }
  21647. return null;
  21648. };
  21649. /**
  21650. * Get a the last added mesh found of a given ID
  21651. * @param {string} id - the id to search for
  21652. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21653. */
  21654. Scene.prototype.getLastMeshByID = function (id) {
  21655. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21656. if (this.meshes[index].id === id) {
  21657. return this.meshes[index];
  21658. }
  21659. }
  21660. return null;
  21661. };
  21662. /**
  21663. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21664. * @param {string} id - the id to search for
  21665. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21666. */
  21667. Scene.prototype.getLastEntryByID = function (id) {
  21668. var index;
  21669. for (index = this.meshes.length - 1; index >= 0; index--) {
  21670. if (this.meshes[index].id === id) {
  21671. return this.meshes[index];
  21672. }
  21673. }
  21674. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21675. if (this.transformNodes[index].id === id) {
  21676. return this.transformNodes[index];
  21677. }
  21678. }
  21679. for (index = this.cameras.length - 1; index >= 0; index--) {
  21680. if (this.cameras[index].id === id) {
  21681. return this.cameras[index];
  21682. }
  21683. }
  21684. for (index = this.lights.length - 1; index >= 0; index--) {
  21685. if (this.lights[index].id === id) {
  21686. return this.lights[index];
  21687. }
  21688. }
  21689. return null;
  21690. };
  21691. Scene.prototype.getNodeByID = function (id) {
  21692. var mesh = this.getMeshByID(id);
  21693. if (mesh) {
  21694. return mesh;
  21695. }
  21696. var light = this.getLightByID(id);
  21697. if (light) {
  21698. return light;
  21699. }
  21700. var camera = this.getCameraByID(id);
  21701. if (camera) {
  21702. return camera;
  21703. }
  21704. var bone = this.getBoneByID(id);
  21705. return bone;
  21706. };
  21707. Scene.prototype.getNodeByName = function (name) {
  21708. var mesh = this.getMeshByName(name);
  21709. if (mesh) {
  21710. return mesh;
  21711. }
  21712. var light = this.getLightByName(name);
  21713. if (light) {
  21714. return light;
  21715. }
  21716. var camera = this.getCameraByName(name);
  21717. if (camera) {
  21718. return camera;
  21719. }
  21720. var bone = this.getBoneByName(name);
  21721. return bone;
  21722. };
  21723. Scene.prototype.getMeshByName = function (name) {
  21724. for (var index = 0; index < this.meshes.length; index++) {
  21725. if (this.meshes[index].name === name) {
  21726. return this.meshes[index];
  21727. }
  21728. }
  21729. return null;
  21730. };
  21731. Scene.prototype.getTransformNodeByName = function (name) {
  21732. for (var index = 0; index < this.transformNodes.length; index++) {
  21733. if (this.transformNodes[index].name === name) {
  21734. return this.transformNodes[index];
  21735. }
  21736. }
  21737. return null;
  21738. };
  21739. Scene.prototype.getSoundByName = function (name) {
  21740. var index;
  21741. if (BABYLON.AudioEngine) {
  21742. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21743. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21744. return this.mainSoundTrack.soundCollection[index];
  21745. }
  21746. }
  21747. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21748. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21749. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21750. return this.soundTracks[sdIndex].soundCollection[index];
  21751. }
  21752. }
  21753. }
  21754. }
  21755. return null;
  21756. };
  21757. Scene.prototype.getLastSkeletonByID = function (id) {
  21758. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21759. if (this.skeletons[index].id === id) {
  21760. return this.skeletons[index];
  21761. }
  21762. }
  21763. return null;
  21764. };
  21765. Scene.prototype.getSkeletonById = function (id) {
  21766. for (var index = 0; index < this.skeletons.length; index++) {
  21767. if (this.skeletons[index].id === id) {
  21768. return this.skeletons[index];
  21769. }
  21770. }
  21771. return null;
  21772. };
  21773. Scene.prototype.getSkeletonByName = function (name) {
  21774. for (var index = 0; index < this.skeletons.length; index++) {
  21775. if (this.skeletons[index].name === name) {
  21776. return this.skeletons[index];
  21777. }
  21778. }
  21779. return null;
  21780. };
  21781. Scene.prototype.getMorphTargetManagerById = function (id) {
  21782. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21783. if (this.morphTargetManagers[index].uniqueId === id) {
  21784. return this.morphTargetManagers[index];
  21785. }
  21786. }
  21787. return null;
  21788. };
  21789. Scene.prototype.isActiveMesh = function (mesh) {
  21790. return (this._activeMeshes.indexOf(mesh) !== -1);
  21791. };
  21792. /**
  21793. * Return a the first highlight layer of the scene with a given name.
  21794. * @param name The name of the highlight layer to look for.
  21795. * @return The highlight layer if found otherwise null.
  21796. */
  21797. Scene.prototype.getHighlightLayerByName = function (name) {
  21798. for (var index = 0; index < this.highlightLayers.length; index++) {
  21799. if (this.highlightLayers[index].name === name) {
  21800. return this.highlightLayers[index];
  21801. }
  21802. }
  21803. return null;
  21804. };
  21805. Object.defineProperty(Scene.prototype, "uid", {
  21806. /**
  21807. * Return a unique id as a string which can serve as an identifier for the scene
  21808. */
  21809. get: function () {
  21810. if (!this._uid) {
  21811. this._uid = BABYLON.Tools.RandomId();
  21812. }
  21813. return this._uid;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. /**
  21819. * Add an externaly attached data from its key.
  21820. * This method call will fail and return false, if such key already exists.
  21821. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21822. * @param key the unique key that identifies the data
  21823. * @param data the data object to associate to the key for this Engine instance
  21824. * @return true if no such key were already present and the data was added successfully, false otherwise
  21825. */
  21826. Scene.prototype.addExternalData = function (key, data) {
  21827. if (!this._externalData) {
  21828. this._externalData = new BABYLON.StringDictionary();
  21829. }
  21830. return this._externalData.add(key, data);
  21831. };
  21832. /**
  21833. * Get an externaly attached data from its key
  21834. * @param key the unique key that identifies the data
  21835. * @return the associated data, if present (can be null), or undefined if not present
  21836. */
  21837. Scene.prototype.getExternalData = function (key) {
  21838. if (!this._externalData) {
  21839. return null;
  21840. }
  21841. return this._externalData.get(key);
  21842. };
  21843. /**
  21844. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21845. * @param key the unique key that identifies the data
  21846. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21847. * @return the associated data, can be null if the factory returned null.
  21848. */
  21849. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21850. if (!this._externalData) {
  21851. this._externalData = new BABYLON.StringDictionary();
  21852. }
  21853. return this._externalData.getOrAddWithFactory(key, factory);
  21854. };
  21855. /**
  21856. * Remove an externaly attached data from the Engine instance
  21857. * @param key the unique key that identifies the data
  21858. * @return true if the data was successfully removed, false if it doesn't exist
  21859. */
  21860. Scene.prototype.removeExternalData = function (key) {
  21861. return this._externalData.remove(key);
  21862. };
  21863. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21864. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21865. if (mesh.showSubMeshesBoundingBox) {
  21866. var boundingInfo = subMesh.getBoundingInfo();
  21867. if (boundingInfo !== null && boundingInfo !== undefined) {
  21868. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21869. }
  21870. }
  21871. var material = subMesh.getMaterial();
  21872. if (material !== null && material !== undefined) {
  21873. // Render targets
  21874. if (material.getRenderTargetTextures !== undefined) {
  21875. if (this._processedMaterials.indexOf(material) === -1) {
  21876. this._processedMaterials.push(material);
  21877. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21878. }
  21879. }
  21880. // Dispatch
  21881. this._activeIndices.addCount(subMesh.indexCount, false);
  21882. this._renderingManager.dispatch(subMesh, mesh, material);
  21883. }
  21884. }
  21885. };
  21886. Scene.prototype._isInIntermediateRendering = function () {
  21887. return this._intermediateRendering;
  21888. };
  21889. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21890. this._activeMeshCandidateProvider = provider;
  21891. };
  21892. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21893. return this._activeMeshCandidateProvider;
  21894. };
  21895. /**
  21896. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21897. */
  21898. Scene.prototype.freezeActiveMeshes = function () {
  21899. this._evaluateActiveMeshes();
  21900. this._activeMeshesFrozen = true;
  21901. return this;
  21902. };
  21903. /**
  21904. * Use this function to restart evaluating active meshes on every frame
  21905. */
  21906. Scene.prototype.unfreezeActiveMeshes = function () {
  21907. this._activeMeshesFrozen = false;
  21908. return this;
  21909. };
  21910. Scene.prototype._evaluateActiveMeshes = function () {
  21911. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21912. return;
  21913. }
  21914. if (!this.activeCamera) {
  21915. return;
  21916. }
  21917. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21918. this.activeCamera._activeMeshes.reset();
  21919. this._activeMeshes.reset();
  21920. this._renderingManager.reset();
  21921. this._processedMaterials.reset();
  21922. this._activeParticleSystems.reset();
  21923. this._activeSkeletons.reset();
  21924. this._softwareSkinnedMeshes.reset();
  21925. if (this._boundingBoxRenderer) {
  21926. this._boundingBoxRenderer.reset();
  21927. }
  21928. // Meshes
  21929. var meshes;
  21930. var len;
  21931. var checkIsEnabled = true;
  21932. // Determine mesh candidates
  21933. if (this._activeMeshCandidateProvider !== undefined) {
  21934. // Use _activeMeshCandidateProvider
  21935. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21936. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21937. if (meshes !== undefined) {
  21938. len = meshes.length;
  21939. }
  21940. else {
  21941. len = 0;
  21942. }
  21943. }
  21944. else if (this._selectionOctree !== undefined) {
  21945. // Octree
  21946. var selection = this._selectionOctree.select(this._frustumPlanes);
  21947. meshes = selection.data;
  21948. len = selection.length;
  21949. }
  21950. else {
  21951. // Full scene traversal
  21952. len = this.meshes.length;
  21953. meshes = this.meshes;
  21954. }
  21955. // Check each mesh
  21956. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21957. mesh = meshes[meshIndex];
  21958. if (mesh.isBlocked) {
  21959. continue;
  21960. }
  21961. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21962. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21963. continue;
  21964. }
  21965. mesh.computeWorldMatrix();
  21966. // Intersections
  21967. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21968. this._meshesForIntersections.pushNoDuplicate(mesh);
  21969. }
  21970. // Switch to current LOD
  21971. meshLOD = mesh.getLOD(this.activeCamera);
  21972. if (meshLOD === undefined || meshLOD === null) {
  21973. continue;
  21974. }
  21975. mesh._preActivate();
  21976. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21977. this._activeMeshes.push(mesh);
  21978. this.activeCamera._activeMeshes.push(mesh);
  21979. mesh._activate(this._renderId);
  21980. if (meshLOD !== mesh) {
  21981. meshLOD._activate(this._renderId);
  21982. }
  21983. this._activeMesh(mesh, meshLOD);
  21984. }
  21985. }
  21986. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21987. // Particle systems
  21988. if (this.particlesEnabled) {
  21989. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21990. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21991. var particleSystem = this.particleSystems[particleIndex];
  21992. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21993. continue;
  21994. }
  21995. var emitter = particleSystem.emitter;
  21996. if (!emitter.position || emitter.isEnabled()) {
  21997. this._activeParticleSystems.push(particleSystem);
  21998. particleSystem.animate();
  21999. this._renderingManager.dispatchParticles(particleSystem);
  22000. }
  22001. }
  22002. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22003. }
  22004. };
  22005. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22006. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22007. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22008. mesh.skeleton.prepare();
  22009. }
  22010. if (!mesh.computeBonesUsingShaders) {
  22011. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22012. }
  22013. }
  22014. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22015. var boundingInfo = sourceMesh.getBoundingInfo();
  22016. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22017. }
  22018. if (mesh !== undefined && mesh !== null
  22019. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22020. // Submeshes Octrees
  22021. var len;
  22022. var subMeshes;
  22023. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22024. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22025. len = intersections.length;
  22026. subMeshes = intersections.data;
  22027. }
  22028. else {
  22029. subMeshes = mesh.subMeshes;
  22030. len = subMeshes.length;
  22031. }
  22032. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22033. subMesh = subMeshes[subIndex];
  22034. this._evaluateSubMesh(subMesh, mesh);
  22035. }
  22036. }
  22037. };
  22038. Scene.prototype.updateTransformMatrix = function (force) {
  22039. if (!this.activeCamera) {
  22040. return;
  22041. }
  22042. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22043. };
  22044. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22045. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22046. };
  22047. Scene.prototype._renderForCamera = function (camera) {
  22048. if (camera && camera._skipRendering) {
  22049. return;
  22050. }
  22051. var engine = this._engine;
  22052. this.activeCamera = camera;
  22053. if (!this.activeCamera)
  22054. throw new Error("Active camera not set");
  22055. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22056. // Viewport
  22057. engine.setViewport(this.activeCamera.viewport);
  22058. // Camera
  22059. this.resetCachedMaterial();
  22060. this._renderId++;
  22061. this.activeCamera.update();
  22062. this.updateTransformMatrix();
  22063. if (camera._alternateCamera) {
  22064. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22065. this._alternateRendering = true;
  22066. }
  22067. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22068. // Meshes
  22069. this._evaluateActiveMeshes();
  22070. // Software skinning
  22071. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22072. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22073. mesh.applySkeleton(mesh.skeleton);
  22074. }
  22075. // Render targets
  22076. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22077. var needsRestoreFrameBuffer = false;
  22078. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22079. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22080. }
  22081. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22082. this._intermediateRendering = true;
  22083. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22084. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22085. var renderTarget = this._renderTargets.data[renderIndex];
  22086. if (renderTarget._shouldRender()) {
  22087. this._renderId++;
  22088. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22089. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22090. }
  22091. }
  22092. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22093. this._intermediateRendering = false;
  22094. this._renderId++;
  22095. needsRestoreFrameBuffer = true; // Restore back buffer
  22096. }
  22097. // Render HighlightLayer Texture
  22098. var stencilState = this._engine.getStencilBuffer();
  22099. var renderhighlights = false;
  22100. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22101. this._intermediateRendering = true;
  22102. for (var i = 0; i < this.highlightLayers.length; i++) {
  22103. var highlightLayer = this.highlightLayers[i];
  22104. if (highlightLayer.shouldRender() &&
  22105. (!highlightLayer.camera ||
  22106. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22107. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22108. renderhighlights = true;
  22109. var renderTarget = highlightLayer._mainTexture;
  22110. if (renderTarget._shouldRender()) {
  22111. this._renderId++;
  22112. renderTarget.render(false, false);
  22113. needsRestoreFrameBuffer = true;
  22114. }
  22115. }
  22116. }
  22117. this._intermediateRendering = false;
  22118. this._renderId++;
  22119. }
  22120. if (needsRestoreFrameBuffer) {
  22121. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22122. }
  22123. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22124. // Prepare Frame
  22125. this.postProcessManager._prepareFrame();
  22126. // Backgrounds
  22127. var layerIndex;
  22128. var layer;
  22129. if (this.layers.length) {
  22130. engine.setDepthBuffer(false);
  22131. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22132. layer = this.layers[layerIndex];
  22133. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22134. layer.render();
  22135. }
  22136. }
  22137. engine.setDepthBuffer(true);
  22138. }
  22139. // Activate HighlightLayer stencil
  22140. if (renderhighlights) {
  22141. this._engine.setStencilBuffer(true);
  22142. }
  22143. // Render
  22144. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22145. this._renderingManager.render(null, null, true, true);
  22146. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22147. // Restore HighlightLayer stencil
  22148. if (renderhighlights) {
  22149. this._engine.setStencilBuffer(stencilState);
  22150. }
  22151. // Bounding boxes
  22152. if (this._boundingBoxRenderer) {
  22153. this._boundingBoxRenderer.render();
  22154. }
  22155. // Lens flares
  22156. if (this.lensFlaresEnabled) {
  22157. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22158. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22159. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22160. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22161. lensFlareSystem.render();
  22162. }
  22163. }
  22164. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22165. }
  22166. // Foregrounds
  22167. if (this.layers.length) {
  22168. engine.setDepthBuffer(false);
  22169. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22170. layer = this.layers[layerIndex];
  22171. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22172. layer.render();
  22173. }
  22174. }
  22175. engine.setDepthBuffer(true);
  22176. }
  22177. // Highlight Layer
  22178. if (renderhighlights) {
  22179. engine.setDepthBuffer(false);
  22180. for (var i = 0; i < this.highlightLayers.length; i++) {
  22181. if (this.highlightLayers[i].shouldRender()) {
  22182. this.highlightLayers[i].render();
  22183. }
  22184. }
  22185. engine.setDepthBuffer(true);
  22186. }
  22187. // Finalize frame
  22188. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22189. // Reset some special arrays
  22190. this._renderTargets.reset();
  22191. this._alternateRendering = false;
  22192. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22193. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22194. };
  22195. Scene.prototype._processSubCameras = function (camera) {
  22196. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22197. this._renderForCamera(camera);
  22198. return;
  22199. }
  22200. // Update camera
  22201. if (this.activeCamera) {
  22202. this.activeCamera.update();
  22203. }
  22204. // rig cameras
  22205. for (var index = 0; index < camera._rigCameras.length; index++) {
  22206. this._renderForCamera(camera._rigCameras[index]);
  22207. }
  22208. this.activeCamera = camera;
  22209. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22210. };
  22211. Scene.prototype._checkIntersections = function () {
  22212. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22213. var sourceMesh = this._meshesForIntersections.data[index];
  22214. if (!sourceMesh.actionManager) {
  22215. continue;
  22216. }
  22217. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22218. var action = sourceMesh.actionManager.actions[actionIndex];
  22219. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22220. var parameters = action.getTriggerParameter();
  22221. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22222. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22223. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22224. if (areIntersecting && currentIntersectionInProgress === -1) {
  22225. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22226. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22227. sourceMesh._intersectionsInProgress.push(otherMesh);
  22228. }
  22229. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22230. sourceMesh._intersectionsInProgress.push(otherMesh);
  22231. }
  22232. }
  22233. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22234. //They intersected, and now they don't.
  22235. //is this trigger an exit trigger? execute an event.
  22236. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22237. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22238. }
  22239. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22240. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22241. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22242. }
  22243. }
  22244. }
  22245. }
  22246. }
  22247. };
  22248. Scene.prototype.render = function () {
  22249. if (this.isDisposed) {
  22250. return;
  22251. }
  22252. this._activeParticles.fetchNewFrame();
  22253. this._totalVertices.fetchNewFrame();
  22254. this._activeIndices.fetchNewFrame();
  22255. this._activeBones.fetchNewFrame();
  22256. this._meshesForIntersections.reset();
  22257. this.resetCachedMaterial();
  22258. this.onBeforeAnimationsObservable.notifyObservers(this);
  22259. // Actions
  22260. if (this.actionManager) {
  22261. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22262. }
  22263. //Simplification Queue
  22264. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22265. this.simplificationQueue.executeNext();
  22266. }
  22267. if (this._engine.isDeterministicLockStep()) {
  22268. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22269. var defaultFPS = (60.0 / 1000.0);
  22270. var defaultFrameTime = 1000 / 60; // frame time in MS
  22271. if (this._physicsEngine) {
  22272. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22273. }
  22274. var stepsTaken = 0;
  22275. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22276. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22277. internalSteps = Math.min(internalSteps, maxSubSteps);
  22278. do {
  22279. this.onBeforeStepObservable.notifyObservers(this);
  22280. // Animations
  22281. this._animationRatio = defaultFrameTime * defaultFPS;
  22282. this._animate();
  22283. this.onAfterAnimationsObservable.notifyObservers(this);
  22284. // Physics
  22285. if (this._physicsEngine) {
  22286. this.onBeforePhysicsObservable.notifyObservers(this);
  22287. this._physicsEngine._step(defaultFrameTime / 1000);
  22288. this.onAfterPhysicsObservable.notifyObservers(this);
  22289. }
  22290. this.onAfterStepObservable.notifyObservers(this);
  22291. this._currentStepId++;
  22292. stepsTaken++;
  22293. deltaTime -= defaultFrameTime;
  22294. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22295. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22296. }
  22297. else {
  22298. // Animations
  22299. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22300. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22301. this._animate();
  22302. this.onAfterAnimationsObservable.notifyObservers(this);
  22303. // Physics
  22304. if (this._physicsEngine) {
  22305. this.onBeforePhysicsObservable.notifyObservers(this);
  22306. this._physicsEngine._step(deltaTime / 1000.0);
  22307. this.onAfterPhysicsObservable.notifyObservers(this);
  22308. }
  22309. }
  22310. // update gamepad manager
  22311. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22312. this._gamepadManager._checkGamepadsStatus();
  22313. }
  22314. // Before render
  22315. this.onBeforeRenderObservable.notifyObservers(this);
  22316. // Customs render targets
  22317. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22318. var engine = this.getEngine();
  22319. var currentActiveCamera = this.activeCamera;
  22320. if (this.renderTargetsEnabled) {
  22321. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22322. this._intermediateRendering = true;
  22323. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22324. var renderTarget = this.customRenderTargets[customIndex];
  22325. if (renderTarget._shouldRender()) {
  22326. this._renderId++;
  22327. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22328. if (!this.activeCamera)
  22329. throw new Error("Active camera not set");
  22330. // Viewport
  22331. engine.setViewport(this.activeCamera.viewport);
  22332. // Camera
  22333. this.updateTransformMatrix();
  22334. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22335. }
  22336. }
  22337. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22338. this._intermediateRendering = false;
  22339. this._renderId++;
  22340. }
  22341. // Restore back buffer
  22342. if (this.customRenderTargets.length > 0) {
  22343. engine.restoreDefaultFramebuffer();
  22344. }
  22345. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22346. this.activeCamera = currentActiveCamera;
  22347. // Procedural textures
  22348. if (this.proceduralTexturesEnabled) {
  22349. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22350. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22351. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22352. if (proceduralTexture._shouldRender()) {
  22353. proceduralTexture.render();
  22354. }
  22355. }
  22356. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22357. }
  22358. // Clear
  22359. if (this.autoClearDepthAndStencil || this.autoClear) {
  22360. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22361. }
  22362. // Shadows
  22363. if (this.shadowsEnabled) {
  22364. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22365. var light = this.lights[lightIndex];
  22366. var shadowGenerator = light.getShadowGenerator();
  22367. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22368. var shadowMap = (shadowGenerator.getShadowMap());
  22369. if (this.textures.indexOf(shadowMap) !== -1) {
  22370. this._renderTargets.push(shadowMap);
  22371. }
  22372. }
  22373. }
  22374. }
  22375. // Depth renderer
  22376. if (this._depthRenderer) {
  22377. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22378. }
  22379. // Geometry renderer
  22380. if (this._geometryBufferRenderer) {
  22381. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22382. }
  22383. // RenderPipeline
  22384. if (this._postProcessRenderPipelineManager) {
  22385. this._postProcessRenderPipelineManager.update();
  22386. }
  22387. // Multi-cameras?
  22388. if (this.activeCameras.length > 0) {
  22389. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22390. if (cameraIndex > 0) {
  22391. this._engine.clear(null, false, true, true);
  22392. }
  22393. this._processSubCameras(this.activeCameras[cameraIndex]);
  22394. }
  22395. }
  22396. else {
  22397. if (!this.activeCamera) {
  22398. throw new Error("No camera defined");
  22399. }
  22400. this._processSubCameras(this.activeCamera);
  22401. }
  22402. // Intersection checks
  22403. this._checkIntersections();
  22404. // Update the audio listener attached to the camera
  22405. if (BABYLON.AudioEngine) {
  22406. this._updateAudioParameters();
  22407. }
  22408. // After render
  22409. if (this.afterRender) {
  22410. this.afterRender();
  22411. }
  22412. this.onAfterRenderObservable.notifyObservers(this);
  22413. // Cleaning
  22414. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22415. var data = this._toBeDisposed.data[index];
  22416. if (data) {
  22417. data.dispose();
  22418. }
  22419. this._toBeDisposed[index] = null;
  22420. }
  22421. this._toBeDisposed.reset();
  22422. if (this.dumpNextRenderTargets) {
  22423. this.dumpNextRenderTargets = false;
  22424. }
  22425. this._activeBones.addCount(0, true);
  22426. this._activeIndices.addCount(0, true);
  22427. this._activeParticles.addCount(0, true);
  22428. };
  22429. Scene.prototype._updateAudioParameters = function () {
  22430. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22431. return;
  22432. }
  22433. var listeningCamera;
  22434. var audioEngine = BABYLON.Engine.audioEngine;
  22435. if (this.activeCameras.length > 0) {
  22436. listeningCamera = this.activeCameras[0];
  22437. }
  22438. else {
  22439. listeningCamera = this.activeCamera;
  22440. }
  22441. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22442. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22443. // for VR cameras
  22444. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22445. listeningCamera = listeningCamera.rigCameras[0];
  22446. }
  22447. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22448. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22449. cameraDirection.normalize();
  22450. // To avoid some errors on GearVR
  22451. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22452. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22453. }
  22454. var i;
  22455. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22456. var sound = this.mainSoundTrack.soundCollection[i];
  22457. if (sound.useCustomAttenuation) {
  22458. sound.updateDistanceFromListener();
  22459. }
  22460. }
  22461. for (i = 0; i < this.soundTracks.length; i++) {
  22462. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22463. sound = this.soundTracks[i].soundCollection[j];
  22464. if (sound.useCustomAttenuation) {
  22465. sound.updateDistanceFromListener();
  22466. }
  22467. }
  22468. }
  22469. }
  22470. };
  22471. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22472. // Audio
  22473. get: function () {
  22474. return this._audioEnabled;
  22475. },
  22476. set: function (value) {
  22477. this._audioEnabled = value;
  22478. if (BABYLON.AudioEngine) {
  22479. if (this._audioEnabled) {
  22480. this._enableAudio();
  22481. }
  22482. else {
  22483. this._disableAudio();
  22484. }
  22485. }
  22486. },
  22487. enumerable: true,
  22488. configurable: true
  22489. });
  22490. Scene.prototype._disableAudio = function () {
  22491. var i;
  22492. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22493. this.mainSoundTrack.soundCollection[i].pause();
  22494. }
  22495. for (i = 0; i < this.soundTracks.length; i++) {
  22496. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22497. this.soundTracks[i].soundCollection[j].pause();
  22498. }
  22499. }
  22500. };
  22501. Scene.prototype._enableAudio = function () {
  22502. var i;
  22503. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22504. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22505. this.mainSoundTrack.soundCollection[i].play();
  22506. }
  22507. }
  22508. for (i = 0; i < this.soundTracks.length; i++) {
  22509. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22510. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22511. this.soundTracks[i].soundCollection[j].play();
  22512. }
  22513. }
  22514. }
  22515. };
  22516. Object.defineProperty(Scene.prototype, "headphone", {
  22517. get: function () {
  22518. return this._headphone;
  22519. },
  22520. set: function (value) {
  22521. this._headphone = value;
  22522. if (BABYLON.AudioEngine) {
  22523. if (this._headphone) {
  22524. this._switchAudioModeForHeadphones();
  22525. }
  22526. else {
  22527. this._switchAudioModeForNormalSpeakers();
  22528. }
  22529. }
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. Scene.prototype._switchAudioModeForHeadphones = function () {
  22535. this.mainSoundTrack.switchPanningModelToHRTF();
  22536. for (var i = 0; i < this.soundTracks.length; i++) {
  22537. this.soundTracks[i].switchPanningModelToHRTF();
  22538. }
  22539. };
  22540. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22541. this.mainSoundTrack.switchPanningModelToEqualPower();
  22542. for (var i = 0; i < this.soundTracks.length; i++) {
  22543. this.soundTracks[i].switchPanningModelToEqualPower();
  22544. }
  22545. };
  22546. Scene.prototype.enableDepthRenderer = function () {
  22547. if (this._depthRenderer) {
  22548. return this._depthRenderer;
  22549. }
  22550. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22551. return this._depthRenderer;
  22552. };
  22553. Scene.prototype.disableDepthRenderer = function () {
  22554. if (!this._depthRenderer) {
  22555. return;
  22556. }
  22557. this._depthRenderer.dispose();
  22558. this._depthRenderer = null;
  22559. };
  22560. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22561. if (ratio === void 0) { ratio = 1; }
  22562. if (this._geometryBufferRenderer) {
  22563. return this._geometryBufferRenderer;
  22564. }
  22565. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22566. if (!this._geometryBufferRenderer.isSupported) {
  22567. this._geometryBufferRenderer = null;
  22568. }
  22569. return this._geometryBufferRenderer;
  22570. };
  22571. Scene.prototype.disableGeometryBufferRenderer = function () {
  22572. if (!this._geometryBufferRenderer) {
  22573. return;
  22574. }
  22575. this._geometryBufferRenderer.dispose();
  22576. this._geometryBufferRenderer = null;
  22577. };
  22578. Scene.prototype.freezeMaterials = function () {
  22579. for (var i = 0; i < this.materials.length; i++) {
  22580. this.materials[i].freeze();
  22581. }
  22582. };
  22583. Scene.prototype.unfreezeMaterials = function () {
  22584. for (var i = 0; i < this.materials.length; i++) {
  22585. this.materials[i].unfreeze();
  22586. }
  22587. };
  22588. Scene.prototype.dispose = function () {
  22589. this.beforeRender = null;
  22590. this.afterRender = null;
  22591. this.skeletons = [];
  22592. this.morphTargetManagers = [];
  22593. this.importedMeshesFiles = new Array();
  22594. this.stopAllAnimations();
  22595. this.resetCachedMaterial();
  22596. if (this._depthRenderer) {
  22597. this._depthRenderer.dispose();
  22598. }
  22599. if (this._gamepadManager) {
  22600. this._gamepadManager.dispose();
  22601. this._gamepadManager = null;
  22602. }
  22603. // Smart arrays
  22604. if (this.activeCamera) {
  22605. this.activeCamera._activeMeshes.dispose();
  22606. this.activeCamera = null;
  22607. }
  22608. this._activeMeshes.dispose();
  22609. this._renderingManager.dispose();
  22610. this._processedMaterials.dispose();
  22611. this._activeParticleSystems.dispose();
  22612. this._activeSkeletons.dispose();
  22613. this._softwareSkinnedMeshes.dispose();
  22614. this._renderTargets.dispose();
  22615. if (this._boundingBoxRenderer) {
  22616. this._boundingBoxRenderer.dispose();
  22617. }
  22618. this._meshesForIntersections.dispose();
  22619. this._toBeDisposed.dispose();
  22620. // Abort active requests
  22621. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22622. var request = _a[_i];
  22623. request.abort();
  22624. }
  22625. // Debug layer
  22626. if (this._debugLayer) {
  22627. this._debugLayer.hide();
  22628. }
  22629. // Events
  22630. this.onDisposeObservable.notifyObservers(this);
  22631. this.onDisposeObservable.clear();
  22632. this.onBeforeRenderObservable.clear();
  22633. this.onAfterRenderObservable.clear();
  22634. this.OnBeforeRenderTargetsRenderObservable.clear();
  22635. this.OnAfterRenderTargetsRenderObservable.clear();
  22636. this.onAfterStepObservable.clear();
  22637. this.onBeforeStepObservable.clear();
  22638. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22639. this.onAfterActiveMeshesEvaluationObservable.clear();
  22640. this.onBeforeParticlesRenderingObservable.clear();
  22641. this.onAfterParticlesRenderingObservable.clear();
  22642. this.onBeforeSpritesRenderingObservable.clear();
  22643. this.onAfterSpritesRenderingObservable.clear();
  22644. this.onBeforeDrawPhaseObservable.clear();
  22645. this.onAfterDrawPhaseObservable.clear();
  22646. this.onBeforePhysicsObservable.clear();
  22647. this.onAfterPhysicsObservable.clear();
  22648. this.onBeforeAnimationsObservable.clear();
  22649. this.onAfterAnimationsObservable.clear();
  22650. this.onDataLoadedObservable.clear();
  22651. this.detachControl();
  22652. // Release sounds & sounds tracks
  22653. if (BABYLON.AudioEngine) {
  22654. this.disposeSounds();
  22655. }
  22656. // VR Helper
  22657. if (this.VRHelper) {
  22658. this.VRHelper.dispose();
  22659. }
  22660. // Detach cameras
  22661. var canvas = this._engine.getRenderingCanvas();
  22662. if (canvas) {
  22663. var index;
  22664. for (index = 0; index < this.cameras.length; index++) {
  22665. this.cameras[index].detachControl(canvas);
  22666. }
  22667. }
  22668. // Release animation groups
  22669. while (this.animationGroups.length) {
  22670. this.animationGroups[0].dispose();
  22671. }
  22672. // Release lights
  22673. while (this.lights.length) {
  22674. this.lights[0].dispose();
  22675. }
  22676. // Release meshes
  22677. while (this.meshes.length) {
  22678. this.meshes[0].dispose(true);
  22679. }
  22680. while (this.transformNodes.length) {
  22681. this.removeTransformNode(this.transformNodes[0]);
  22682. }
  22683. // Release cameras
  22684. while (this.cameras.length) {
  22685. this.cameras[0].dispose();
  22686. }
  22687. // Release materials
  22688. if (this.defaultMaterial) {
  22689. this.defaultMaterial.dispose();
  22690. }
  22691. while (this.multiMaterials.length) {
  22692. this.multiMaterials[0].dispose();
  22693. }
  22694. while (this.materials.length) {
  22695. this.materials[0].dispose();
  22696. }
  22697. // Release particles
  22698. while (this.particleSystems.length) {
  22699. this.particleSystems[0].dispose();
  22700. }
  22701. // Release sprites
  22702. while (this.spriteManagers.length) {
  22703. this.spriteManagers[0].dispose();
  22704. }
  22705. // Release postProcesses
  22706. while (this.postProcesses.length) {
  22707. this.postProcesses[0].dispose();
  22708. }
  22709. // Release layers
  22710. while (this.layers.length) {
  22711. this.layers[0].dispose();
  22712. }
  22713. while (this.highlightLayers.length) {
  22714. this.highlightLayers[0].dispose();
  22715. }
  22716. // Release textures
  22717. while (this.textures.length) {
  22718. this.textures[0].dispose();
  22719. }
  22720. // Release UBO
  22721. this._sceneUbo.dispose();
  22722. if (this._alternateSceneUbo) {
  22723. this._alternateSceneUbo.dispose();
  22724. }
  22725. // Post-processes
  22726. this.postProcessManager.dispose();
  22727. if (this._postProcessRenderPipelineManager) {
  22728. this._postProcessRenderPipelineManager.dispose();
  22729. }
  22730. // Physics
  22731. if (this._physicsEngine) {
  22732. this.disablePhysicsEngine();
  22733. }
  22734. // Remove from engine
  22735. index = this._engine.scenes.indexOf(this);
  22736. if (index > -1) {
  22737. this._engine.scenes.splice(index, 1);
  22738. }
  22739. this._engine.wipeCaches(true);
  22740. this._isDisposed = true;
  22741. };
  22742. Object.defineProperty(Scene.prototype, "isDisposed", {
  22743. get: function () {
  22744. return this._isDisposed;
  22745. },
  22746. enumerable: true,
  22747. configurable: true
  22748. });
  22749. // Release sounds & sounds tracks
  22750. Scene.prototype.disposeSounds = function () {
  22751. if (!this._mainSoundTrack) {
  22752. return;
  22753. }
  22754. this.mainSoundTrack.dispose();
  22755. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22756. this.soundTracks[scIndex].dispose();
  22757. }
  22758. };
  22759. // Octrees
  22760. Scene.prototype.getWorldExtends = function () {
  22761. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22762. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22763. for (var index = 0; index < this.meshes.length; index++) {
  22764. var mesh = this.meshes[index];
  22765. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22766. continue;
  22767. }
  22768. mesh.computeWorldMatrix(true);
  22769. var boundingInfo = mesh.getBoundingInfo();
  22770. var minBox = boundingInfo.boundingBox.minimumWorld;
  22771. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22772. BABYLON.Tools.CheckExtends(minBox, min, max);
  22773. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22774. }
  22775. return {
  22776. min: min,
  22777. max: max
  22778. };
  22779. };
  22780. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22781. if (maxCapacity === void 0) { maxCapacity = 64; }
  22782. if (maxDepth === void 0) { maxDepth = 2; }
  22783. if (!this._selectionOctree) {
  22784. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22785. }
  22786. var worldExtends = this.getWorldExtends();
  22787. // Update octree
  22788. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22789. return this._selectionOctree;
  22790. };
  22791. // Picking
  22792. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22793. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22794. var result = BABYLON.Ray.Zero();
  22795. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22796. return result;
  22797. };
  22798. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22799. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22800. var engine = this._engine;
  22801. if (!camera) {
  22802. if (!this.activeCamera)
  22803. throw new Error("Active camera not set");
  22804. camera = this.activeCamera;
  22805. }
  22806. var cameraViewport = camera.viewport;
  22807. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22808. // Moving coordinates to local viewport world
  22809. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22810. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22811. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22812. return this;
  22813. };
  22814. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22815. var result = BABYLON.Ray.Zero();
  22816. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22817. return result;
  22818. };
  22819. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22820. if (!BABYLON.PickingInfo) {
  22821. return this;
  22822. }
  22823. var engine = this._engine;
  22824. if (!camera) {
  22825. if (!this.activeCamera)
  22826. throw new Error("Active camera not set");
  22827. camera = this.activeCamera;
  22828. }
  22829. var cameraViewport = camera.viewport;
  22830. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22831. var identity = BABYLON.Matrix.Identity();
  22832. // Moving coordinates to local viewport world
  22833. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22834. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22835. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22836. return this;
  22837. };
  22838. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22839. if (!BABYLON.PickingInfo) {
  22840. return null;
  22841. }
  22842. var pickingInfo = null;
  22843. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22844. var mesh = this.meshes[meshIndex];
  22845. if (predicate) {
  22846. if (!predicate(mesh)) {
  22847. continue;
  22848. }
  22849. }
  22850. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22851. continue;
  22852. }
  22853. var world = mesh.getWorldMatrix();
  22854. var ray = rayFunction(world);
  22855. var result = mesh.intersects(ray, fastCheck);
  22856. if (!result || !result.hit)
  22857. continue;
  22858. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22859. continue;
  22860. pickingInfo = result;
  22861. if (fastCheck) {
  22862. break;
  22863. }
  22864. }
  22865. return pickingInfo || new BABYLON.PickingInfo();
  22866. };
  22867. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22868. if (!BABYLON.PickingInfo) {
  22869. return null;
  22870. }
  22871. var pickingInfos = new Array();
  22872. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22873. var mesh = this.meshes[meshIndex];
  22874. if (predicate) {
  22875. if (!predicate(mesh)) {
  22876. continue;
  22877. }
  22878. }
  22879. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22880. continue;
  22881. }
  22882. var world = mesh.getWorldMatrix();
  22883. var ray = rayFunction(world);
  22884. var result = mesh.intersects(ray, false);
  22885. if (!result || !result.hit)
  22886. continue;
  22887. pickingInfos.push(result);
  22888. }
  22889. return pickingInfos;
  22890. };
  22891. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22892. if (!BABYLON.PickingInfo) {
  22893. return null;
  22894. }
  22895. var pickingInfo = null;
  22896. if (!camera) {
  22897. if (!this.activeCamera) {
  22898. return null;
  22899. }
  22900. camera = this.activeCamera;
  22901. }
  22902. if (this.spriteManagers.length > 0) {
  22903. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22904. var spriteManager = this.spriteManagers[spriteIndex];
  22905. if (!spriteManager.isPickable) {
  22906. continue;
  22907. }
  22908. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22909. if (!result || !result.hit)
  22910. continue;
  22911. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22912. continue;
  22913. pickingInfo = result;
  22914. if (fastCheck) {
  22915. break;
  22916. }
  22917. }
  22918. }
  22919. return pickingInfo || new BABYLON.PickingInfo();
  22920. };
  22921. /** Launch a ray to try to pick a mesh in the scene
  22922. * @param x position on screen
  22923. * @param y position on screen
  22924. * @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
  22925. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22926. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22927. */
  22928. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22929. var _this = this;
  22930. if (!BABYLON.PickingInfo) {
  22931. return null;
  22932. }
  22933. return this._internalPick(function (world) {
  22934. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22935. return _this._tempPickingRay;
  22936. }, predicate, fastCheck);
  22937. };
  22938. /** Launch a ray to try to pick a sprite in the scene
  22939. * @param x position on screen
  22940. * @param y position on screen
  22941. * @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
  22942. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22943. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22944. */
  22945. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22946. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22947. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22948. };
  22949. /** Use the given ray to pick a mesh in the scene
  22950. * @param ray The ray to use to pick meshes
  22951. * @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
  22952. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22953. */
  22954. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22955. var _this = this;
  22956. return this._internalPick(function (world) {
  22957. if (!_this._pickWithRayInverseMatrix) {
  22958. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22959. }
  22960. world.invertToRef(_this._pickWithRayInverseMatrix);
  22961. if (!_this._cachedRayForTransform) {
  22962. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22963. }
  22964. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22965. return _this._cachedRayForTransform;
  22966. }, predicate, fastCheck);
  22967. };
  22968. /**
  22969. * Launch a ray to try to pick a mesh in the scene
  22970. * @param x X position on screen
  22971. * @param y Y position on screen
  22972. * @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
  22973. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22974. */
  22975. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22976. var _this = this;
  22977. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22978. };
  22979. /**
  22980. * Launch a ray to try to pick a mesh in the scene
  22981. * @param ray Ray to use
  22982. * @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
  22983. */
  22984. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22985. var _this = this;
  22986. return this._internalMultiPick(function (world) {
  22987. if (!_this._pickWithRayInverseMatrix) {
  22988. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22989. }
  22990. world.invertToRef(_this._pickWithRayInverseMatrix);
  22991. if (!_this._cachedRayForTransform) {
  22992. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22993. }
  22994. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22995. return _this._cachedRayForTransform;
  22996. }, predicate);
  22997. };
  22998. Scene.prototype.setPointerOverMesh = function (mesh) {
  22999. if (this._pointerOverMesh === mesh) {
  23000. return;
  23001. }
  23002. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23003. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23004. }
  23005. this._pointerOverMesh = mesh;
  23006. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23007. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23008. }
  23009. };
  23010. Scene.prototype.getPointerOverMesh = function () {
  23011. return this._pointerOverMesh;
  23012. };
  23013. Scene.prototype.setPointerOverSprite = function (sprite) {
  23014. if (this._pointerOverSprite === sprite) {
  23015. return;
  23016. }
  23017. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23018. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23019. }
  23020. this._pointerOverSprite = sprite;
  23021. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23022. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23023. }
  23024. };
  23025. Scene.prototype.getPointerOverSprite = function () {
  23026. return this._pointerOverSprite;
  23027. };
  23028. // Physics
  23029. Scene.prototype.getPhysicsEngine = function () {
  23030. return this._physicsEngine;
  23031. };
  23032. /**
  23033. * Enables physics to the current scene
  23034. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23035. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23036. * @return {boolean} was the physics engine initialized
  23037. */
  23038. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23039. if (gravity === void 0) { gravity = null; }
  23040. if (this._physicsEngine) {
  23041. return true;
  23042. }
  23043. try {
  23044. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23045. return true;
  23046. }
  23047. catch (e) {
  23048. BABYLON.Tools.Error(e.message);
  23049. return false;
  23050. }
  23051. };
  23052. Scene.prototype.disablePhysicsEngine = function () {
  23053. if (!this._physicsEngine) {
  23054. return;
  23055. }
  23056. this._physicsEngine.dispose();
  23057. this._physicsEngine = null;
  23058. };
  23059. Scene.prototype.isPhysicsEnabled = function () {
  23060. return this._physicsEngine !== undefined;
  23061. };
  23062. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23063. var mesh = compound.parts[0].mesh;
  23064. if (mesh.physicsImpostor) {
  23065. mesh.physicsImpostor.dispose();
  23066. mesh.physicsImpostor = null;
  23067. }
  23068. };
  23069. // Misc.
  23070. Scene.prototype._rebuildGeometries = function () {
  23071. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23072. var geometry = _a[_i];
  23073. geometry._rebuild();
  23074. }
  23075. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23076. var mesh = _c[_b];
  23077. mesh._rebuild();
  23078. }
  23079. if (this.postProcessManager) {
  23080. this.postProcessManager._rebuild();
  23081. }
  23082. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23083. var layer = _e[_d];
  23084. layer._rebuild();
  23085. }
  23086. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23087. var highlightLayer = _g[_f];
  23088. highlightLayer._rebuild();
  23089. }
  23090. if (this._boundingBoxRenderer) {
  23091. this._boundingBoxRenderer._rebuild();
  23092. }
  23093. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23094. var system = _j[_h];
  23095. system.rebuild();
  23096. }
  23097. if (this._postProcessRenderPipelineManager) {
  23098. this._postProcessRenderPipelineManager._rebuild();
  23099. }
  23100. };
  23101. Scene.prototype._rebuildTextures = function () {
  23102. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23103. var texture = _a[_i];
  23104. texture._rebuild();
  23105. }
  23106. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23107. };
  23108. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23109. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23110. if (replace === void 0) { replace = false; }
  23111. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23112. // Dispose existing camera or light in replace mode.
  23113. if (replace) {
  23114. if (this.activeCamera) {
  23115. this.activeCamera.dispose();
  23116. this.activeCamera = null;
  23117. }
  23118. if (this.lights) {
  23119. for (var i = 0; i < this.lights.length; i++) {
  23120. this.lights[i].dispose();
  23121. }
  23122. }
  23123. }
  23124. // Light
  23125. if (this.lights.length === 0) {
  23126. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23127. }
  23128. // Camera
  23129. if (!this.activeCamera) {
  23130. var worldExtends = this.getWorldExtends();
  23131. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23132. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23133. var camera;
  23134. var radius = worldSize.length() * 1.5;
  23135. if (createArcRotateCamera) {
  23136. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23137. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23138. arcRotateCamera.wheelPrecision = 100 / radius;
  23139. camera = arcRotateCamera;
  23140. }
  23141. else {
  23142. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23143. freeCamera.setTarget(worldCenter);
  23144. camera = freeCamera;
  23145. }
  23146. camera.minZ = radius * 0.01;
  23147. camera.maxZ = radius * 1000;
  23148. camera.speed = radius * 0.2;
  23149. this.activeCamera = camera;
  23150. var canvas = this.getEngine().getRenderingCanvas();
  23151. if (attachCameraControls && canvas) {
  23152. camera.attachControl(canvas);
  23153. }
  23154. }
  23155. };
  23156. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23157. if (pbr === void 0) { pbr = false; }
  23158. if (scale === void 0) { scale = 1000; }
  23159. if (blur === void 0) { blur = 0; }
  23160. if (environmentTexture) {
  23161. this.environmentTexture = environmentTexture;
  23162. }
  23163. if (!this.environmentTexture) {
  23164. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23165. return null;
  23166. }
  23167. // Skybox
  23168. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23169. if (pbr) {
  23170. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23171. hdrSkyboxMaterial.backFaceCulling = false;
  23172. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23173. if (hdrSkyboxMaterial.reflectionTexture) {
  23174. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23175. }
  23176. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23177. hdrSkyboxMaterial.disableLighting = true;
  23178. hdrSkyboxMaterial.twoSidedLighting = true;
  23179. hdrSkybox.infiniteDistance = true;
  23180. hdrSkybox.material = hdrSkyboxMaterial;
  23181. }
  23182. else {
  23183. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23184. skyboxMaterial.backFaceCulling = false;
  23185. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23186. if (skyboxMaterial.reflectionTexture) {
  23187. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23188. }
  23189. skyboxMaterial.disableLighting = true;
  23190. hdrSkybox.infiniteDistance = true;
  23191. hdrSkybox.material = skyboxMaterial;
  23192. }
  23193. return hdrSkybox;
  23194. };
  23195. Scene.prototype.createDefaultEnvironment = function (options) {
  23196. if (BABYLON.EnvironmentHelper) {
  23197. return new BABYLON.EnvironmentHelper(options, this);
  23198. }
  23199. return null;
  23200. };
  23201. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23202. if (webVROptions === void 0) { webVROptions = {}; }
  23203. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23204. };
  23205. // Tags
  23206. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23207. if (tagsQuery === undefined) {
  23208. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23209. return list;
  23210. }
  23211. var listByTags = [];
  23212. forEach = forEach || (function (item) { return; });
  23213. for (var i in list) {
  23214. var item = list[i];
  23215. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23216. listByTags.push(item);
  23217. forEach(item);
  23218. }
  23219. }
  23220. return listByTags;
  23221. };
  23222. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23223. return this._getByTags(this.meshes, tagsQuery, forEach);
  23224. };
  23225. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23226. return this._getByTags(this.cameras, tagsQuery, forEach);
  23227. };
  23228. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23229. return this._getByTags(this.lights, tagsQuery, forEach);
  23230. };
  23231. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23232. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23233. };
  23234. /**
  23235. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23236. * This allowed control for front to back rendering or reversly depending of the special needs.
  23237. *
  23238. * @param renderingGroupId The rendering group id corresponding to its index
  23239. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23240. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23241. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23242. */
  23243. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23244. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23245. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23246. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23247. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23248. };
  23249. /**
  23250. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23251. *
  23252. * @param renderingGroupId The rendering group id corresponding to its index
  23253. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23254. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23255. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23256. */
  23257. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23258. if (depth === void 0) { depth = true; }
  23259. if (stencil === void 0) { stencil = true; }
  23260. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23261. };
  23262. /**
  23263. * Will flag all materials as dirty to trigger new shader compilation
  23264. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23265. */
  23266. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23267. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23268. var material = _a[_i];
  23269. if (predicate && !predicate(material)) {
  23270. continue;
  23271. }
  23272. material.markAsDirty(flag);
  23273. }
  23274. };
  23275. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23276. var _this = this;
  23277. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23278. this._activeRequests.push(request);
  23279. request.onCompleteObservable.add(function (request) {
  23280. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23281. });
  23282. return request;
  23283. };
  23284. // Statics
  23285. Scene._FOGMODE_NONE = 0;
  23286. Scene._FOGMODE_EXP = 1;
  23287. Scene._FOGMODE_EXP2 = 2;
  23288. Scene._FOGMODE_LINEAR = 3;
  23289. Scene._uniqueIdCounter = 0;
  23290. Scene.MinDeltaTime = 1.0;
  23291. Scene.MaxDeltaTime = 1000.0;
  23292. /** The distance in pixel that you have to move to prevent some events */
  23293. Scene.DragMovementThreshold = 10; // in pixels
  23294. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23295. Scene.LongPressDelay = 500; // in milliseconds
  23296. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23297. Scene.DoubleClickDelay = 300; // in milliseconds
  23298. /** If you need to check double click without raising a single click at first click, enable this flag */
  23299. Scene.ExclusiveDoubleClickMode = false;
  23300. return Scene;
  23301. }());
  23302. BABYLON.Scene = Scene;
  23303. })(BABYLON || (BABYLON = {}));
  23304. //# sourceMappingURL=babylon.scene.js.map
  23305. var BABYLON;
  23306. (function (BABYLON) {
  23307. /**
  23308. * Set of assets to keep when moving a scene into an asset container.
  23309. */
  23310. var KeepAssets = /** @class */ (function () {
  23311. function KeepAssets() {
  23312. /**
  23313. * Cameras to keep.
  23314. */
  23315. this.cameras = new Array();
  23316. /**
  23317. * Lights to keep.
  23318. */
  23319. this.lights = new Array();
  23320. /**
  23321. * Meshes to keep.
  23322. */
  23323. this.meshes = new Array();
  23324. /**
  23325. * Skeletons to keep.
  23326. */
  23327. this.skeletons = new Array();
  23328. /**
  23329. * ParticleSystems to keep.
  23330. */
  23331. this.particleSystems = new Array();
  23332. /**
  23333. * Animations to keep.
  23334. */
  23335. this.animations = new Array();
  23336. /**
  23337. * MultiMaterials to keep.
  23338. */
  23339. this.multiMaterials = new Array();
  23340. /**
  23341. * Materials to keep.
  23342. */
  23343. this.materials = new Array();
  23344. /**
  23345. * MorphTargetManagers to keep.
  23346. */
  23347. this.morphTargetManagers = new Array();
  23348. /**
  23349. * Geometries to keep.
  23350. */
  23351. this.geometries = new Array();
  23352. /**
  23353. * TransformNodes to keep.
  23354. */
  23355. this.transformNodes = new Array();
  23356. /**
  23357. * LensFlareSystems to keep.
  23358. */
  23359. this.lensFlareSystems = new Array();
  23360. /**
  23361. * ShadowGenerators to keep.
  23362. */
  23363. this.shadowGenerators = new Array();
  23364. /**
  23365. * ActionManagers to keep.
  23366. */
  23367. this.actionManagers = new Array();
  23368. /**
  23369. * Sounds to keep.
  23370. */
  23371. this.sounds = new Array();
  23372. }
  23373. return KeepAssets;
  23374. }());
  23375. BABYLON.KeepAssets = KeepAssets;
  23376. /**
  23377. * Container with a set of assets that can be added or removed from a scene.
  23378. */
  23379. var AssetContainer = /** @class */ (function () {
  23380. /**
  23381. * Instantiates an AssetContainer.
  23382. * @param scene The scene the AssetContainer belongs to.
  23383. */
  23384. function AssetContainer(scene) {
  23385. // Objects
  23386. /**
  23387. * Cameras populated in the container.
  23388. */
  23389. this.cameras = new Array();
  23390. /**
  23391. * Lights populated in the container.
  23392. */
  23393. this.lights = new Array();
  23394. /**
  23395. * Meshes populated in the container.
  23396. */
  23397. this.meshes = new Array();
  23398. /**
  23399. * Skeletons populated in the container.
  23400. */
  23401. this.skeletons = new Array();
  23402. /**
  23403. * ParticleSystems populated in the container.
  23404. */
  23405. this.particleSystems = new Array();
  23406. /**
  23407. * Animations populated in the container.
  23408. */
  23409. this.animations = new Array();
  23410. /**
  23411. * MultiMaterials populated in the container.
  23412. */
  23413. this.multiMaterials = new Array();
  23414. /**
  23415. * Materials populated in the container.
  23416. */
  23417. this.materials = new Array();
  23418. /**
  23419. * MorphTargetManagers populated in the container.
  23420. */
  23421. this.morphTargetManagers = new Array();
  23422. /**
  23423. * Geometries populated in the container.
  23424. */
  23425. this.geometries = new Array();
  23426. /**
  23427. * TransformNodes populated in the container.
  23428. */
  23429. this.transformNodes = new Array();
  23430. /**
  23431. * LensFlareSystems populated in the container.
  23432. */
  23433. this.lensFlareSystems = new Array();
  23434. /**
  23435. * ShadowGenerators populated in the container.
  23436. */
  23437. this.shadowGenerators = new Array();
  23438. /**
  23439. * ActionManagers populated in the container.
  23440. */
  23441. this.actionManagers = new Array();
  23442. /**
  23443. * Sounds populated in the container.
  23444. */
  23445. this.sounds = new Array();
  23446. this.scene = scene;
  23447. }
  23448. /**
  23449. * Adds all the assets from the container to the scene.
  23450. */
  23451. AssetContainer.prototype.addAllToScene = function () {
  23452. var _this = this;
  23453. this.cameras.forEach(function (o) {
  23454. _this.scene.addCamera(o);
  23455. });
  23456. this.lights.forEach(function (o) {
  23457. _this.scene.addLight(o);
  23458. });
  23459. this.meshes.forEach(function (o) {
  23460. _this.scene.addMesh(o);
  23461. });
  23462. this.skeletons.forEach(function (o) {
  23463. _this.scene.addSkeleton(o);
  23464. });
  23465. this.particleSystems.forEach(function (o) {
  23466. _this.scene.addParticleSystem(o);
  23467. });
  23468. this.animations.forEach(function (o) {
  23469. _this.scene.addAnimation(o);
  23470. });
  23471. this.multiMaterials.forEach(function (o) {
  23472. _this.scene.addMultiMaterial(o);
  23473. });
  23474. this.materials.forEach(function (o) {
  23475. _this.scene.addMaterial(o);
  23476. });
  23477. this.morphTargetManagers.forEach(function (o) {
  23478. _this.scene.addMorphTargetManager(o);
  23479. });
  23480. this.geometries.forEach(function (o) {
  23481. _this.scene.addGeometry(o);
  23482. });
  23483. this.transformNodes.forEach(function (o) {
  23484. _this.scene.addTransformNode(o);
  23485. });
  23486. this.lensFlareSystems.forEach(function (o) {
  23487. _this.scene.addLensFlareSystem(o);
  23488. });
  23489. this.actionManagers.forEach(function (o) {
  23490. _this.scene.addActionManager(o);
  23491. });
  23492. this.sounds.forEach(function (o) {
  23493. o.play();
  23494. o.autoplay = true;
  23495. _this.scene.mainSoundTrack.AddSound(o);
  23496. });
  23497. };
  23498. /**
  23499. * Removes all the assets in the container from the scene
  23500. */
  23501. AssetContainer.prototype.removeAllFromScene = function () {
  23502. var _this = this;
  23503. this.cameras.forEach(function (o) {
  23504. _this.scene.removeCamera(o);
  23505. });
  23506. this.lights.forEach(function (o) {
  23507. _this.scene.removeLight(o);
  23508. });
  23509. this.meshes.forEach(function (o) {
  23510. _this.scene.removeMesh(o);
  23511. });
  23512. this.skeletons.forEach(function (o) {
  23513. _this.scene.removeSkeleton(o);
  23514. });
  23515. this.particleSystems.forEach(function (o) {
  23516. _this.scene.removeParticleSystem(o);
  23517. });
  23518. this.animations.forEach(function (o) {
  23519. _this.scene.removeAnimation(o);
  23520. });
  23521. this.multiMaterials.forEach(function (o) {
  23522. _this.scene.removeMultiMaterial(o);
  23523. });
  23524. this.materials.forEach(function (o) {
  23525. _this.scene.removeMaterial(o);
  23526. });
  23527. this.morphTargetManagers.forEach(function (o) {
  23528. _this.scene.removeMorphTargetManager(o);
  23529. });
  23530. this.geometries.forEach(function (o) {
  23531. _this.scene.removeGeometry(o);
  23532. });
  23533. this.transformNodes.forEach(function (o) {
  23534. _this.scene.removeTransformNode(o);
  23535. });
  23536. this.lensFlareSystems.forEach(function (o) {
  23537. _this.scene.removeLensFlareSystem(o);
  23538. });
  23539. this.actionManagers.forEach(function (o) {
  23540. _this.scene.removeActionManager(o);
  23541. });
  23542. this.sounds.forEach(function (o) {
  23543. o.stop();
  23544. o.autoplay = false;
  23545. _this.scene.mainSoundTrack.RemoveSound(o);
  23546. });
  23547. };
  23548. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  23549. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  23550. var asset = sourceAssets_1[_i];
  23551. var move = true;
  23552. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  23553. var keepAsset = keepAssets_1[_a];
  23554. if (asset === keepAsset) {
  23555. move = false;
  23556. break;
  23557. }
  23558. }
  23559. if (move) {
  23560. targetAssets.push(asset);
  23561. }
  23562. }
  23563. };
  23564. /**
  23565. * Removes all the assets contained in the scene and adds them to the container.
  23566. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  23567. */
  23568. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  23569. if (keepAssets === undefined) {
  23570. keepAssets = new KeepAssets();
  23571. }
  23572. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  23573. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  23574. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  23575. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  23576. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  23577. Array.prototype.push.apply(this.animations, this.scene.animations);
  23578. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  23579. Array.prototype.push.apply(this.lights, this.scene.lights);
  23580. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  23581. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  23582. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  23583. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  23584. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  23585. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  23586. this.removeAllFromScene();
  23587. };
  23588. return AssetContainer;
  23589. }());
  23590. BABYLON.AssetContainer = AssetContainer;
  23591. })(BABYLON || (BABYLON = {}));
  23592. //# sourceMappingURL=babylon.assetContainer.js.map
  23593. var BABYLON;
  23594. (function (BABYLON) {
  23595. var Buffer = /** @class */ (function () {
  23596. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23597. if (instanced === void 0) { instanced = false; }
  23598. if (engine instanceof BABYLON.Mesh) {
  23599. this._engine = engine.getScene().getEngine();
  23600. }
  23601. else {
  23602. this._engine = engine;
  23603. }
  23604. this._updatable = updatable;
  23605. this._data = data;
  23606. this._strideSize = stride;
  23607. if (!postponeInternalCreation) {
  23608. this.create();
  23609. }
  23610. this._instanced = instanced;
  23611. this._instanceDivisor = instanced ? 1 : 0;
  23612. }
  23613. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23614. // a lot of these parameters are ignored as they are overriden by the buffer
  23615. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23616. };
  23617. // Properties
  23618. Buffer.prototype.isUpdatable = function () {
  23619. return this._updatable;
  23620. };
  23621. Buffer.prototype.getData = function () {
  23622. return this._data;
  23623. };
  23624. Buffer.prototype.getBuffer = function () {
  23625. return this._buffer;
  23626. };
  23627. Buffer.prototype.getStrideSize = function () {
  23628. return this._strideSize;
  23629. };
  23630. Buffer.prototype.getIsInstanced = function () {
  23631. return this._instanced;
  23632. };
  23633. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23634. get: function () {
  23635. return this._instanceDivisor;
  23636. },
  23637. set: function (value) {
  23638. this._instanceDivisor = value;
  23639. if (value == 0) {
  23640. this._instanced = false;
  23641. }
  23642. else {
  23643. this._instanced = true;
  23644. }
  23645. },
  23646. enumerable: true,
  23647. configurable: true
  23648. });
  23649. // Methods
  23650. Buffer.prototype.create = function (data) {
  23651. if (data === void 0) { data = null; }
  23652. if (!data && this._buffer) {
  23653. return; // nothing to do
  23654. }
  23655. data = data || this._data;
  23656. if (!data) {
  23657. return;
  23658. }
  23659. if (!this._buffer) {
  23660. if (this._updatable) {
  23661. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23662. this._data = data;
  23663. }
  23664. else {
  23665. this._buffer = this._engine.createVertexBuffer(data);
  23666. }
  23667. }
  23668. else if (this._updatable) {
  23669. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23670. this._data = data;
  23671. }
  23672. };
  23673. Buffer.prototype._rebuild = function () {
  23674. this._buffer = null;
  23675. this.create(this._data);
  23676. };
  23677. Buffer.prototype.update = function (data) {
  23678. this.create(data);
  23679. };
  23680. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23681. if (!this._buffer) {
  23682. return;
  23683. }
  23684. if (this._updatable) {
  23685. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23686. this._data = null;
  23687. }
  23688. };
  23689. Buffer.prototype.dispose = function () {
  23690. if (!this._buffer) {
  23691. return;
  23692. }
  23693. if (this._engine._releaseBuffer(this._buffer)) {
  23694. this._buffer = null;
  23695. }
  23696. };
  23697. return Buffer;
  23698. }());
  23699. BABYLON.Buffer = Buffer;
  23700. })(BABYLON || (BABYLON = {}));
  23701. //# sourceMappingURL=babylon.buffer.js.map
  23702. var BABYLON;
  23703. (function (BABYLON) {
  23704. var VertexBuffer = /** @class */ (function () {
  23705. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23706. if (!stride) {
  23707. // Deduce stride from kind
  23708. switch (kind) {
  23709. case VertexBuffer.PositionKind:
  23710. stride = 3;
  23711. break;
  23712. case VertexBuffer.NormalKind:
  23713. stride = 3;
  23714. break;
  23715. case VertexBuffer.UVKind:
  23716. case VertexBuffer.UV2Kind:
  23717. case VertexBuffer.UV3Kind:
  23718. case VertexBuffer.UV4Kind:
  23719. case VertexBuffer.UV5Kind:
  23720. case VertexBuffer.UV6Kind:
  23721. stride = 2;
  23722. break;
  23723. case VertexBuffer.TangentKind:
  23724. case VertexBuffer.ColorKind:
  23725. stride = 4;
  23726. break;
  23727. case VertexBuffer.MatricesIndicesKind:
  23728. case VertexBuffer.MatricesIndicesExtraKind:
  23729. stride = 4;
  23730. break;
  23731. case VertexBuffer.MatricesWeightsKind:
  23732. case VertexBuffer.MatricesWeightsExtraKind:
  23733. default:
  23734. stride = 4;
  23735. break;
  23736. }
  23737. }
  23738. if (data instanceof BABYLON.Buffer) {
  23739. if (!stride) {
  23740. stride = data.getStrideSize();
  23741. }
  23742. this._buffer = data;
  23743. this._ownsBuffer = false;
  23744. }
  23745. else {
  23746. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23747. this._ownsBuffer = true;
  23748. }
  23749. this._stride = stride;
  23750. this._offset = offset ? offset : 0;
  23751. this._size = size ? size : stride;
  23752. this._kind = kind;
  23753. }
  23754. VertexBuffer.prototype._rebuild = function () {
  23755. if (!this._buffer) {
  23756. return;
  23757. }
  23758. this._buffer._rebuild();
  23759. };
  23760. /**
  23761. * Returns the kind of the VertexBuffer (string).
  23762. */
  23763. VertexBuffer.prototype.getKind = function () {
  23764. return this._kind;
  23765. };
  23766. // Properties
  23767. /**
  23768. * Boolean : is the VertexBuffer updatable ?
  23769. */
  23770. VertexBuffer.prototype.isUpdatable = function () {
  23771. return this._buffer.isUpdatable();
  23772. };
  23773. /**
  23774. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23775. */
  23776. VertexBuffer.prototype.getData = function () {
  23777. return this._buffer.getData();
  23778. };
  23779. /**
  23780. * Returns the WebGLBuffer associated to the VertexBuffer.
  23781. */
  23782. VertexBuffer.prototype.getBuffer = function () {
  23783. return this._buffer.getBuffer();
  23784. };
  23785. /**
  23786. * Returns the stride of the VertexBuffer (integer).
  23787. */
  23788. VertexBuffer.prototype.getStrideSize = function () {
  23789. return this._stride;
  23790. };
  23791. /**
  23792. * Returns the offset (integer).
  23793. */
  23794. VertexBuffer.prototype.getOffset = function () {
  23795. return this._offset;
  23796. };
  23797. /**
  23798. * Returns the VertexBuffer total size (integer).
  23799. */
  23800. VertexBuffer.prototype.getSize = function () {
  23801. return this._size;
  23802. };
  23803. /**
  23804. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23805. */
  23806. VertexBuffer.prototype.getIsInstanced = function () {
  23807. return this._buffer.getIsInstanced();
  23808. };
  23809. /**
  23810. * Returns the instancing divisor, zero for non-instanced (integer).
  23811. */
  23812. VertexBuffer.prototype.getInstanceDivisor = function () {
  23813. return this._buffer.instanceDivisor;
  23814. };
  23815. // Methods
  23816. /**
  23817. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23818. * Returns the created WebGLBuffer.
  23819. */
  23820. VertexBuffer.prototype.create = function (data) {
  23821. return this._buffer.create(data);
  23822. };
  23823. /**
  23824. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23825. * This function will create a new buffer if the current one is not updatable
  23826. * Returns the updated WebGLBuffer.
  23827. */
  23828. VertexBuffer.prototype.update = function (data) {
  23829. return this._buffer.update(data);
  23830. };
  23831. /**
  23832. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23833. * Returns the directly updated WebGLBuffer.
  23834. */
  23835. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23836. return this._buffer.updateDirectly(data, offset);
  23837. };
  23838. /**
  23839. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23840. */
  23841. VertexBuffer.prototype.dispose = function () {
  23842. if (this._ownsBuffer) {
  23843. this._buffer.dispose();
  23844. }
  23845. };
  23846. Object.defineProperty(VertexBuffer, "PositionKind", {
  23847. get: function () {
  23848. return VertexBuffer._PositionKind;
  23849. },
  23850. enumerable: true,
  23851. configurable: true
  23852. });
  23853. Object.defineProperty(VertexBuffer, "NormalKind", {
  23854. get: function () {
  23855. return VertexBuffer._NormalKind;
  23856. },
  23857. enumerable: true,
  23858. configurable: true
  23859. });
  23860. Object.defineProperty(VertexBuffer, "TangentKind", {
  23861. get: function () {
  23862. return VertexBuffer._TangentKind;
  23863. },
  23864. enumerable: true,
  23865. configurable: true
  23866. });
  23867. Object.defineProperty(VertexBuffer, "UVKind", {
  23868. get: function () {
  23869. return VertexBuffer._UVKind;
  23870. },
  23871. enumerable: true,
  23872. configurable: true
  23873. });
  23874. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23875. get: function () {
  23876. return VertexBuffer._UV2Kind;
  23877. },
  23878. enumerable: true,
  23879. configurable: true
  23880. });
  23881. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23882. get: function () {
  23883. return VertexBuffer._UV3Kind;
  23884. },
  23885. enumerable: true,
  23886. configurable: true
  23887. });
  23888. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23889. get: function () {
  23890. return VertexBuffer._UV4Kind;
  23891. },
  23892. enumerable: true,
  23893. configurable: true
  23894. });
  23895. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23896. get: function () {
  23897. return VertexBuffer._UV5Kind;
  23898. },
  23899. enumerable: true,
  23900. configurable: true
  23901. });
  23902. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23903. get: function () {
  23904. return VertexBuffer._UV6Kind;
  23905. },
  23906. enumerable: true,
  23907. configurable: true
  23908. });
  23909. Object.defineProperty(VertexBuffer, "ColorKind", {
  23910. get: function () {
  23911. return VertexBuffer._ColorKind;
  23912. },
  23913. enumerable: true,
  23914. configurable: true
  23915. });
  23916. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23917. get: function () {
  23918. return VertexBuffer._MatricesIndicesKind;
  23919. },
  23920. enumerable: true,
  23921. configurable: true
  23922. });
  23923. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23924. get: function () {
  23925. return VertexBuffer._MatricesWeightsKind;
  23926. },
  23927. enumerable: true,
  23928. configurable: true
  23929. });
  23930. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23931. get: function () {
  23932. return VertexBuffer._MatricesIndicesExtraKind;
  23933. },
  23934. enumerable: true,
  23935. configurable: true
  23936. });
  23937. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23938. get: function () {
  23939. return VertexBuffer._MatricesWeightsExtraKind;
  23940. },
  23941. enumerable: true,
  23942. configurable: true
  23943. });
  23944. // Enums
  23945. VertexBuffer._PositionKind = "position";
  23946. VertexBuffer._NormalKind = "normal";
  23947. VertexBuffer._TangentKind = "tangent";
  23948. VertexBuffer._UVKind = "uv";
  23949. VertexBuffer._UV2Kind = "uv2";
  23950. VertexBuffer._UV3Kind = "uv3";
  23951. VertexBuffer._UV4Kind = "uv4";
  23952. VertexBuffer._UV5Kind = "uv5";
  23953. VertexBuffer._UV6Kind = "uv6";
  23954. VertexBuffer._ColorKind = "color";
  23955. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23956. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23957. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23958. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23959. return VertexBuffer;
  23960. }());
  23961. BABYLON.VertexBuffer = VertexBuffer;
  23962. })(BABYLON || (BABYLON = {}));
  23963. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23964. var BABYLON;
  23965. (function (BABYLON) {
  23966. /**
  23967. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  23968. */
  23969. var DummyInternalTextureTracker = /** @class */ (function () {
  23970. function DummyInternalTextureTracker() {
  23971. /**
  23972. * Gets or set the previous tracker in the list
  23973. */
  23974. this.previous = null;
  23975. /**
  23976. * Gets or set the next tracker in the list
  23977. */
  23978. this.next = null;
  23979. }
  23980. return DummyInternalTextureTracker;
  23981. }());
  23982. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  23983. })(BABYLON || (BABYLON = {}));
  23984. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  23985. var BABYLON;
  23986. (function (BABYLON) {
  23987. /**
  23988. * Class used to store data associated with WebGL texture data for the engine
  23989. * This class should not be used directly
  23990. */
  23991. var InternalTexture = /** @class */ (function () {
  23992. /**
  23993. * Creates a new InternalTexture
  23994. * @param engine defines the engine to use
  23995. * @param dataSource defines the type of data that will be used
  23996. */
  23997. function InternalTexture(engine, dataSource) {
  23998. /**
  23999. * Observable called when the texture is loaded
  24000. */
  24001. this.onLoadedObservable = new BABYLON.Observable();
  24002. /**
  24003. * Gets or set the previous tracker in the list
  24004. */
  24005. this.previous = null;
  24006. /**
  24007. * Gets or set the next tracker in the list
  24008. */
  24009. this.next = null;
  24010. // Private
  24011. /** @ignore */
  24012. this._initialSlot = -1;
  24013. /** @ignore */
  24014. this._designatedSlot = -1;
  24015. /** @ignore */
  24016. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24017. /** @ignore */
  24018. this._references = 1;
  24019. this._engine = engine;
  24020. this._dataSource = dataSource;
  24021. this._webGLTexture = engine._createTexture();
  24022. }
  24023. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24024. /**
  24025. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24026. */
  24027. get: function () {
  24028. return this._dataSource;
  24029. },
  24030. enumerable: true,
  24031. configurable: true
  24032. });
  24033. /**
  24034. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24035. */
  24036. InternalTexture.prototype.incrementReferences = function () {
  24037. this._references++;
  24038. };
  24039. /**
  24040. * Change the size of the texture (not the size of the content)
  24041. * @param width defines the new width
  24042. * @param height defines the new height
  24043. * @param depth defines the new depth (1 by default)
  24044. */
  24045. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24046. if (depth === void 0) { depth = 1; }
  24047. this.width = width;
  24048. this.height = height;
  24049. this.depth = depth;
  24050. this.baseWidth = width;
  24051. this.baseHeight = height;
  24052. this.baseDepth = depth;
  24053. this._size = width * height * depth;
  24054. };
  24055. /** @ignore */
  24056. InternalTexture.prototype._rebuild = function () {
  24057. var _this = this;
  24058. var proxy;
  24059. this.isReady = false;
  24060. this._cachedCoordinatesMode = null;
  24061. this._cachedWrapU = null;
  24062. this._cachedWrapV = null;
  24063. this._cachedAnisotropicFilteringLevel = null;
  24064. switch (this._dataSource) {
  24065. case InternalTexture.DATASOURCE_TEMP:
  24066. return;
  24067. case InternalTexture.DATASOURCE_URL:
  24068. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24069. _this.isReady = true;
  24070. }, null, this._buffer, undefined, this.format);
  24071. proxy._swapAndDie(this);
  24072. return;
  24073. case InternalTexture.DATASOURCE_RAW:
  24074. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24075. proxy._swapAndDie(this);
  24076. this.isReady = true;
  24077. return;
  24078. case InternalTexture.DATASOURCE_RAW3D:
  24079. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24080. proxy._swapAndDie(this);
  24081. this.isReady = true;
  24082. return;
  24083. case InternalTexture.DATASOURCE_DYNAMIC:
  24084. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24085. proxy._swapAndDie(this);
  24086. // The engine will make sure to update content so no need to flag it as isReady = true
  24087. return;
  24088. case InternalTexture.DATASOURCE_RENDERTARGET:
  24089. var options = new BABYLON.RenderTargetCreationOptions();
  24090. options.generateDepthBuffer = this._generateDepthBuffer;
  24091. options.generateMipMaps = this.generateMipMaps;
  24092. options.generateStencilBuffer = this._generateStencilBuffer;
  24093. options.samplingMode = this.samplingMode;
  24094. options.type = this.type;
  24095. if (this.isCube) {
  24096. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24097. }
  24098. else {
  24099. var size = {
  24100. width: this.width,
  24101. height: this.height
  24102. };
  24103. proxy = this._engine.createRenderTargetTexture(size, options);
  24104. }
  24105. proxy._swapAndDie(this);
  24106. this.isReady = true;
  24107. return;
  24108. case InternalTexture.DATASOURCE_CUBE:
  24109. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24110. _this.isReady = true;
  24111. }, null, this.format, this._extension);
  24112. proxy._swapAndDie(this);
  24113. return;
  24114. case InternalTexture.DATASOURCE_CUBERAW:
  24115. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24116. proxy._swapAndDie(this);
  24117. this.isReady = true;
  24118. return;
  24119. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24120. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24121. if (proxy) {
  24122. proxy._swapAndDie(_this);
  24123. }
  24124. _this.isReady = true;
  24125. }, null, this.format, this._extension);
  24126. return;
  24127. }
  24128. };
  24129. InternalTexture.prototype._swapAndDie = function (target) {
  24130. target._webGLTexture = this._webGLTexture;
  24131. if (this._framebuffer) {
  24132. target._framebuffer = this._framebuffer;
  24133. }
  24134. if (this._depthStencilBuffer) {
  24135. target._depthStencilBuffer = this._depthStencilBuffer;
  24136. }
  24137. if (this._lodTextureHigh) {
  24138. if (target._lodTextureHigh) {
  24139. target._lodTextureHigh.dispose();
  24140. }
  24141. target._lodTextureHigh = this._lodTextureHigh;
  24142. }
  24143. if (this._lodTextureMid) {
  24144. if (target._lodTextureMid) {
  24145. target._lodTextureMid.dispose();
  24146. }
  24147. target._lodTextureMid = this._lodTextureMid;
  24148. }
  24149. if (this._lodTextureLow) {
  24150. if (target._lodTextureLow) {
  24151. target._lodTextureLow.dispose();
  24152. }
  24153. target._lodTextureLow = this._lodTextureLow;
  24154. }
  24155. var cache = this._engine.getLoadedTexturesCache();
  24156. var index = cache.indexOf(this);
  24157. if (index !== -1) {
  24158. cache.splice(index, 1);
  24159. }
  24160. };
  24161. /**
  24162. * Dispose the current allocated resources
  24163. */
  24164. InternalTexture.prototype.dispose = function () {
  24165. if (!this._webGLTexture) {
  24166. return;
  24167. }
  24168. this._references--;
  24169. if (this._references === 0) {
  24170. this._engine._releaseTexture(this);
  24171. this._webGLTexture = null;
  24172. this.previous = null;
  24173. this.next = null;
  24174. }
  24175. };
  24176. /**
  24177. * The source of the texture data is unknown
  24178. */
  24179. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24180. /**
  24181. * Texture data comes from an URL
  24182. */
  24183. InternalTexture.DATASOURCE_URL = 1;
  24184. /**
  24185. * Texture data is only used for temporary storage
  24186. */
  24187. InternalTexture.DATASOURCE_TEMP = 2;
  24188. /**
  24189. * Texture data comes from raw data (ArrayBuffer)
  24190. */
  24191. InternalTexture.DATASOURCE_RAW = 3;
  24192. /**
  24193. * Texture content is dynamic (video or dynamic texture)
  24194. */
  24195. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24196. /**
  24197. * Texture content is generated by rendering to it
  24198. */
  24199. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24200. /**
  24201. * Texture content is part of a multi render target process
  24202. */
  24203. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24204. /**
  24205. * Texture data comes from a cube data file
  24206. */
  24207. InternalTexture.DATASOURCE_CUBE = 7;
  24208. /**
  24209. * Texture data comes from a raw cube data
  24210. */
  24211. InternalTexture.DATASOURCE_CUBERAW = 8;
  24212. /**
  24213. * Texture data come from a prefiltered cube data file
  24214. */
  24215. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24216. /**
  24217. * Texture content is raw 3D data
  24218. */
  24219. InternalTexture.DATASOURCE_RAW3D = 10;
  24220. return InternalTexture;
  24221. }());
  24222. BABYLON.InternalTexture = InternalTexture;
  24223. })(BABYLON || (BABYLON = {}));
  24224. //# sourceMappingURL=babylon.internalTexture.js.map
  24225. var BABYLON;
  24226. (function (BABYLON) {
  24227. var BaseTexture = /** @class */ (function () {
  24228. function BaseTexture(scene) {
  24229. this._hasAlpha = false;
  24230. this.getAlphaFromRGB = false;
  24231. this.level = 1;
  24232. this.coordinatesIndex = 0;
  24233. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24234. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24235. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24236. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24237. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24238. this.isCube = false;
  24239. this.is3D = false;
  24240. this.gammaSpace = true;
  24241. this.invertZ = false;
  24242. this.lodLevelInAlpha = false;
  24243. this.lodGenerationOffset = 0.0;
  24244. this.lodGenerationScale = 0.8;
  24245. this.isRenderTarget = false;
  24246. this.animations = new Array();
  24247. /**
  24248. * An event triggered when the texture is disposed.
  24249. * @type {BABYLON.Observable}
  24250. */
  24251. this.onDisposeObservable = new BABYLON.Observable();
  24252. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24253. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24254. if (this._scene) {
  24255. this._scene.textures.push(this);
  24256. }
  24257. this._uid = null;
  24258. }
  24259. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24260. get: function () {
  24261. return this._hasAlpha;
  24262. },
  24263. set: function (value) {
  24264. if (this._hasAlpha === value) {
  24265. return;
  24266. }
  24267. this._hasAlpha = value;
  24268. if (this._scene) {
  24269. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24270. }
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24276. get: function () {
  24277. return this._coordinatesMode;
  24278. },
  24279. set: function (value) {
  24280. if (this._coordinatesMode === value) {
  24281. return;
  24282. }
  24283. this._coordinatesMode = value;
  24284. if (this._scene) {
  24285. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24286. }
  24287. },
  24288. enumerable: true,
  24289. configurable: true
  24290. });
  24291. Object.defineProperty(BaseTexture.prototype, "uid", {
  24292. get: function () {
  24293. if (!this._uid) {
  24294. this._uid = BABYLON.Tools.RandomId();
  24295. }
  24296. return this._uid;
  24297. },
  24298. enumerable: true,
  24299. configurable: true
  24300. });
  24301. BaseTexture.prototype.toString = function () {
  24302. return this.name;
  24303. };
  24304. BaseTexture.prototype.getClassName = function () {
  24305. return "BaseTexture";
  24306. };
  24307. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24308. set: function (callback) {
  24309. if (this._onDisposeObserver) {
  24310. this.onDisposeObservable.remove(this._onDisposeObserver);
  24311. }
  24312. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24313. },
  24314. enumerable: true,
  24315. configurable: true
  24316. });
  24317. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24318. get: function () {
  24319. return true;
  24320. },
  24321. enumerable: true,
  24322. configurable: true
  24323. });
  24324. BaseTexture.prototype.getScene = function () {
  24325. return this._scene;
  24326. };
  24327. BaseTexture.prototype.getTextureMatrix = function () {
  24328. return BABYLON.Matrix.IdentityReadOnly;
  24329. };
  24330. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24331. return BABYLON.Matrix.IdentityReadOnly;
  24332. };
  24333. BaseTexture.prototype.getInternalTexture = function () {
  24334. return this._texture;
  24335. };
  24336. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24337. return !this.isBlocking || this.isReady();
  24338. };
  24339. BaseTexture.prototype.isReady = function () {
  24340. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24341. this.delayLoad();
  24342. return false;
  24343. }
  24344. if (this._texture) {
  24345. return this._texture.isReady;
  24346. }
  24347. return false;
  24348. };
  24349. BaseTexture.prototype.getSize = function () {
  24350. if (this._texture && this._texture.width) {
  24351. return new BABYLON.Size(this._texture.width, this._texture.height);
  24352. }
  24353. if (this._texture && this._texture._size) {
  24354. return new BABYLON.Size(this._texture._size, this._texture._size);
  24355. }
  24356. return BABYLON.Size.Zero();
  24357. };
  24358. BaseTexture.prototype.getBaseSize = function () {
  24359. if (!this.isReady() || !this._texture)
  24360. return BABYLON.Size.Zero();
  24361. if (this._texture._size) {
  24362. return new BABYLON.Size(this._texture._size, this._texture._size);
  24363. }
  24364. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24365. };
  24366. BaseTexture.prototype.scale = function (ratio) {
  24367. };
  24368. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24369. get: function () {
  24370. return false;
  24371. },
  24372. enumerable: true,
  24373. configurable: true
  24374. });
  24375. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24376. if (!this._scene) {
  24377. return null;
  24378. }
  24379. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24380. for (var index = 0; index < texturesCache.length; index++) {
  24381. var texturesCacheEntry = texturesCache[index];
  24382. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24383. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24384. texturesCacheEntry.incrementReferences();
  24385. return texturesCacheEntry;
  24386. }
  24387. }
  24388. }
  24389. return null;
  24390. };
  24391. BaseTexture.prototype._rebuild = function () {
  24392. };
  24393. BaseTexture.prototype.delayLoad = function () {
  24394. };
  24395. BaseTexture.prototype.clone = function () {
  24396. return null;
  24397. };
  24398. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24399. get: function () {
  24400. if (!this._texture) {
  24401. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24402. }
  24403. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24404. },
  24405. enumerable: true,
  24406. configurable: true
  24407. });
  24408. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24409. get: function () {
  24410. if (!this._texture) {
  24411. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24412. }
  24413. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24414. },
  24415. enumerable: true,
  24416. configurable: true
  24417. });
  24418. BaseTexture.prototype.readPixels = function (faceIndex) {
  24419. if (faceIndex === void 0) { faceIndex = 0; }
  24420. if (!this._texture) {
  24421. return null;
  24422. }
  24423. var size = this.getSize();
  24424. var scene = this.getScene();
  24425. if (!scene) {
  24426. return null;
  24427. }
  24428. var engine = scene.getEngine();
  24429. if (this._texture.isCube) {
  24430. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24431. }
  24432. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24433. };
  24434. BaseTexture.prototype.releaseInternalTexture = function () {
  24435. if (this._texture) {
  24436. this._texture.dispose();
  24437. this._texture = null;
  24438. }
  24439. };
  24440. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24441. get: function () {
  24442. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24443. return null;
  24444. }
  24445. if (!this._texture._sphericalPolynomial) {
  24446. this._texture._sphericalPolynomial =
  24447. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24448. }
  24449. return this._texture._sphericalPolynomial;
  24450. },
  24451. set: function (value) {
  24452. if (this._texture) {
  24453. this._texture._sphericalPolynomial = value;
  24454. }
  24455. },
  24456. enumerable: true,
  24457. configurable: true
  24458. });
  24459. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24460. get: function () {
  24461. if (this._texture) {
  24462. return this._texture._lodTextureHigh;
  24463. }
  24464. return null;
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24470. get: function () {
  24471. if (this._texture) {
  24472. return this._texture._lodTextureMid;
  24473. }
  24474. return null;
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24480. get: function () {
  24481. if (this._texture) {
  24482. return this._texture._lodTextureLow;
  24483. }
  24484. return null;
  24485. },
  24486. enumerable: true,
  24487. configurable: true
  24488. });
  24489. BaseTexture.prototype.dispose = function () {
  24490. if (!this._scene) {
  24491. return;
  24492. }
  24493. // Animations
  24494. this._scene.stopAnimation(this);
  24495. // Remove from scene
  24496. this._scene._removePendingData(this);
  24497. var index = this._scene.textures.indexOf(this);
  24498. if (index >= 0) {
  24499. this._scene.textures.splice(index, 1);
  24500. }
  24501. if (this._texture === undefined) {
  24502. return;
  24503. }
  24504. // Release
  24505. this.releaseInternalTexture();
  24506. // Callback
  24507. this.onDisposeObservable.notifyObservers(this);
  24508. this.onDisposeObservable.clear();
  24509. };
  24510. BaseTexture.prototype.serialize = function () {
  24511. if (!this.name) {
  24512. return null;
  24513. }
  24514. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24515. // Animations
  24516. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24517. return serializationObject;
  24518. };
  24519. BaseTexture.WhenAllReady = function (textures, callback) {
  24520. var numRemaining = textures.length;
  24521. if (numRemaining === 0) {
  24522. callback();
  24523. return;
  24524. }
  24525. var _loop_1 = function () {
  24526. texture = textures[i];
  24527. if (texture.isReady()) {
  24528. if (--numRemaining === 0) {
  24529. callback();
  24530. }
  24531. }
  24532. else {
  24533. onLoadObservable = texture.onLoadObservable;
  24534. var onLoadCallback_1 = function () {
  24535. onLoadObservable.removeCallback(onLoadCallback_1);
  24536. if (--numRemaining === 0) {
  24537. callback();
  24538. }
  24539. };
  24540. onLoadObservable.add(onLoadCallback_1);
  24541. }
  24542. };
  24543. var texture, onLoadObservable;
  24544. for (var i = 0; i < textures.length; i++) {
  24545. _loop_1();
  24546. }
  24547. };
  24548. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24549. __decorate([
  24550. BABYLON.serialize()
  24551. ], BaseTexture.prototype, "name", void 0);
  24552. __decorate([
  24553. BABYLON.serialize("hasAlpha")
  24554. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24555. __decorate([
  24556. BABYLON.serialize()
  24557. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24558. __decorate([
  24559. BABYLON.serialize()
  24560. ], BaseTexture.prototype, "level", void 0);
  24561. __decorate([
  24562. BABYLON.serialize()
  24563. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24564. __decorate([
  24565. BABYLON.serialize("coordinatesMode")
  24566. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24567. __decorate([
  24568. BABYLON.serialize()
  24569. ], BaseTexture.prototype, "wrapU", void 0);
  24570. __decorate([
  24571. BABYLON.serialize()
  24572. ], BaseTexture.prototype, "wrapV", void 0);
  24573. __decorate([
  24574. BABYLON.serialize()
  24575. ], BaseTexture.prototype, "wrapR", void 0);
  24576. __decorate([
  24577. BABYLON.serialize()
  24578. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24579. __decorate([
  24580. BABYLON.serialize()
  24581. ], BaseTexture.prototype, "isCube", void 0);
  24582. __decorate([
  24583. BABYLON.serialize()
  24584. ], BaseTexture.prototype, "is3D", void 0);
  24585. __decorate([
  24586. BABYLON.serialize()
  24587. ], BaseTexture.prototype, "gammaSpace", void 0);
  24588. __decorate([
  24589. BABYLON.serialize()
  24590. ], BaseTexture.prototype, "invertZ", void 0);
  24591. __decorate([
  24592. BABYLON.serialize()
  24593. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24594. __decorate([
  24595. BABYLON.serialize()
  24596. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24597. __decorate([
  24598. BABYLON.serialize()
  24599. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24600. __decorate([
  24601. BABYLON.serialize()
  24602. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24603. return BaseTexture;
  24604. }());
  24605. BABYLON.BaseTexture = BaseTexture;
  24606. })(BABYLON || (BABYLON = {}));
  24607. //# sourceMappingURL=babylon.baseTexture.js.map
  24608. var BABYLON;
  24609. (function (BABYLON) {
  24610. var Texture = /** @class */ (function (_super) {
  24611. __extends(Texture, _super);
  24612. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24613. if (noMipmap === void 0) { noMipmap = false; }
  24614. if (invertY === void 0) { invertY = true; }
  24615. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24616. if (onLoad === void 0) { onLoad = null; }
  24617. if (onError === void 0) { onError = null; }
  24618. if (buffer === void 0) { buffer = null; }
  24619. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24620. var _this = _super.call(this, scene) || this;
  24621. _this.uOffset = 0;
  24622. _this.vOffset = 0;
  24623. _this.uScale = 1.0;
  24624. _this.vScale = 1.0;
  24625. _this.uAng = 0;
  24626. _this.vAng = 0;
  24627. _this.wAng = 0;
  24628. _this._isBlocking = true;
  24629. _this.name = url || "";
  24630. _this.url = url;
  24631. _this._noMipmap = noMipmap;
  24632. _this._invertY = invertY;
  24633. _this._samplingMode = samplingMode;
  24634. _this._buffer = buffer;
  24635. _this._deleteBuffer = deleteBuffer;
  24636. if (format) {
  24637. _this._format = format;
  24638. }
  24639. scene = _this.getScene();
  24640. if (!scene) {
  24641. return _this;
  24642. }
  24643. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24644. var load = function () {
  24645. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24646. _this.onLoadObservable.notifyObservers(_this);
  24647. }
  24648. if (onLoad) {
  24649. onLoad();
  24650. }
  24651. if (!_this.isBlocking && scene) {
  24652. scene.resetCachedMaterial();
  24653. }
  24654. };
  24655. if (!_this.url) {
  24656. _this._delayedOnLoad = load;
  24657. _this._delayedOnError = onError;
  24658. return _this;
  24659. }
  24660. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24661. if (!_this._texture) {
  24662. if (!scene.useDelayedTextureLoading) {
  24663. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24664. if (deleteBuffer) {
  24665. delete _this._buffer;
  24666. }
  24667. }
  24668. else {
  24669. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24670. _this._delayedOnLoad = load;
  24671. _this._delayedOnError = onError;
  24672. }
  24673. }
  24674. else {
  24675. if (_this._texture.isReady) {
  24676. BABYLON.Tools.SetImmediate(function () { return load(); });
  24677. }
  24678. else {
  24679. _this._texture.onLoadedObservable.add(load);
  24680. }
  24681. }
  24682. return _this;
  24683. }
  24684. Object.defineProperty(Texture.prototype, "noMipmap", {
  24685. get: function () {
  24686. return this._noMipmap;
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Texture.prototype, "isBlocking", {
  24692. get: function () {
  24693. return this._isBlocking;
  24694. },
  24695. set: function (value) {
  24696. this._isBlocking = value;
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. Object.defineProperty(Texture.prototype, "samplingMode", {
  24702. get: function () {
  24703. return this._samplingMode;
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. Texture.prototype.updateURL = function (url) {
  24709. this.url = url;
  24710. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24711. this.delayLoad();
  24712. };
  24713. Texture.prototype.delayLoad = function () {
  24714. var _this = this;
  24715. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24716. return;
  24717. }
  24718. var scene = this.getScene();
  24719. if (!scene) {
  24720. return;
  24721. }
  24722. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24723. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24724. if (!this._texture) {
  24725. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24726. if (this._deleteBuffer) {
  24727. delete this._buffer;
  24728. }
  24729. }
  24730. else {
  24731. if (this._texture.isReady) {
  24732. BABYLON.Tools.SetImmediate(function () {
  24733. if (!_this._delayedOnLoad) {
  24734. return;
  24735. }
  24736. _this._delayedOnLoad();
  24737. });
  24738. }
  24739. else {
  24740. if (this._delayedOnLoad) {
  24741. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24742. }
  24743. }
  24744. }
  24745. };
  24746. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24747. if (!this._texture) {
  24748. return;
  24749. }
  24750. var scene = this.getScene();
  24751. if (!scene) {
  24752. return;
  24753. }
  24754. this._samplingMode = samplingMode;
  24755. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24756. };
  24757. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24758. x *= this.uScale;
  24759. y *= this.vScale;
  24760. x -= 0.5 * this.uScale;
  24761. y -= 0.5 * this.vScale;
  24762. z -= 0.5;
  24763. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24764. t.x += 0.5 * this.uScale + this.uOffset;
  24765. t.y += 0.5 * this.vScale + this.vOffset;
  24766. t.z += 0.5;
  24767. };
  24768. Texture.prototype.getTextureMatrix = function () {
  24769. var _this = this;
  24770. if (this.uOffset === this._cachedUOffset &&
  24771. this.vOffset === this._cachedVOffset &&
  24772. this.uScale === this._cachedUScale &&
  24773. this.vScale === this._cachedVScale &&
  24774. this.uAng === this._cachedUAng &&
  24775. this.vAng === this._cachedVAng &&
  24776. this.wAng === this._cachedWAng) {
  24777. return this._cachedTextureMatrix;
  24778. }
  24779. this._cachedUOffset = this.uOffset;
  24780. this._cachedVOffset = this.vOffset;
  24781. this._cachedUScale = this.uScale;
  24782. this._cachedVScale = this.vScale;
  24783. this._cachedUAng = this.uAng;
  24784. this._cachedVAng = this.vAng;
  24785. this._cachedWAng = this.wAng;
  24786. if (!this._cachedTextureMatrix) {
  24787. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24788. this._rowGenerationMatrix = new BABYLON.Matrix();
  24789. this._t0 = BABYLON.Vector3.Zero();
  24790. this._t1 = BABYLON.Vector3.Zero();
  24791. this._t2 = BABYLON.Vector3.Zero();
  24792. }
  24793. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24794. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24795. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24796. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24797. this._t1.subtractInPlace(this._t0);
  24798. this._t2.subtractInPlace(this._t0);
  24799. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24800. this._cachedTextureMatrix.m[0] = this._t1.x;
  24801. this._cachedTextureMatrix.m[1] = this._t1.y;
  24802. this._cachedTextureMatrix.m[2] = this._t1.z;
  24803. this._cachedTextureMatrix.m[4] = this._t2.x;
  24804. this._cachedTextureMatrix.m[5] = this._t2.y;
  24805. this._cachedTextureMatrix.m[6] = this._t2.z;
  24806. this._cachedTextureMatrix.m[8] = this._t0.x;
  24807. this._cachedTextureMatrix.m[9] = this._t0.y;
  24808. this._cachedTextureMatrix.m[10] = this._t0.z;
  24809. var scene = this.getScene();
  24810. if (!scene) {
  24811. return this._cachedTextureMatrix;
  24812. }
  24813. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24814. return mat.hasTexture(_this);
  24815. });
  24816. return this._cachedTextureMatrix;
  24817. };
  24818. Texture.prototype.getReflectionTextureMatrix = function () {
  24819. var _this = this;
  24820. var scene = this.getScene();
  24821. if (!scene) {
  24822. return this._cachedTextureMatrix;
  24823. }
  24824. if (this.uOffset === this._cachedUOffset &&
  24825. this.vOffset === this._cachedVOffset &&
  24826. this.uScale === this._cachedUScale &&
  24827. this.vScale === this._cachedVScale &&
  24828. this.coordinatesMode === this._cachedCoordinatesMode) {
  24829. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24830. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24831. return this._cachedTextureMatrix;
  24832. }
  24833. }
  24834. else {
  24835. return this._cachedTextureMatrix;
  24836. }
  24837. }
  24838. if (!this._cachedTextureMatrix) {
  24839. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24840. }
  24841. if (!this._projectionModeMatrix) {
  24842. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24843. }
  24844. this._cachedUOffset = this.uOffset;
  24845. this._cachedVOffset = this.vOffset;
  24846. this._cachedUScale = this.uScale;
  24847. this._cachedVScale = this.vScale;
  24848. this._cachedCoordinatesMode = this.coordinatesMode;
  24849. switch (this.coordinatesMode) {
  24850. case Texture.PLANAR_MODE:
  24851. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24852. this._cachedTextureMatrix[0] = this.uScale;
  24853. this._cachedTextureMatrix[5] = this.vScale;
  24854. this._cachedTextureMatrix[12] = this.uOffset;
  24855. this._cachedTextureMatrix[13] = this.vOffset;
  24856. break;
  24857. case Texture.PROJECTION_MODE:
  24858. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24859. this._projectionModeMatrix.m[0] = 0.5;
  24860. this._projectionModeMatrix.m[5] = -0.5;
  24861. this._projectionModeMatrix.m[10] = 0.0;
  24862. this._projectionModeMatrix.m[12] = 0.5;
  24863. this._projectionModeMatrix.m[13] = 0.5;
  24864. this._projectionModeMatrix.m[14] = 1.0;
  24865. this._projectionModeMatrix.m[15] = 1.0;
  24866. var projectionMatrix = scene.getProjectionMatrix();
  24867. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24868. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24869. break;
  24870. default:
  24871. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24872. break;
  24873. }
  24874. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24875. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24876. });
  24877. return this._cachedTextureMatrix;
  24878. };
  24879. Texture.prototype.clone = function () {
  24880. var _this = this;
  24881. return BABYLON.SerializationHelper.Clone(function () {
  24882. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24883. }, this);
  24884. };
  24885. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24886. get: function () {
  24887. if (!this._onLoadObservable) {
  24888. this._onLoadObservable = new BABYLON.Observable();
  24889. }
  24890. return this._onLoadObservable;
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. Texture.prototype.serialize = function () {
  24896. var serializationObject = _super.prototype.serialize.call(this);
  24897. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24898. serializationObject.base64String = this._buffer;
  24899. serializationObject.name = serializationObject.name.replace("data:", "");
  24900. }
  24901. return serializationObject;
  24902. };
  24903. Texture.prototype.getClassName = function () {
  24904. return "Texture";
  24905. };
  24906. Texture.prototype.dispose = function () {
  24907. _super.prototype.dispose.call(this);
  24908. if (this.onLoadObservable) {
  24909. this.onLoadObservable.clear();
  24910. this._onLoadObservable = null;
  24911. }
  24912. this._delayedOnLoad = null;
  24913. this._delayedOnError = null;
  24914. };
  24915. // Statics
  24916. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24917. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24918. if (onLoad === void 0) { onLoad = null; }
  24919. if (onError === void 0) { onError = null; }
  24920. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24921. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24922. };
  24923. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24924. if (parsedTexture.customType) {
  24925. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24926. // Update Sampling Mode
  24927. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24928. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24929. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24930. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24931. }
  24932. }
  24933. return parsedCustomTexture;
  24934. }
  24935. if (parsedTexture.isCube) {
  24936. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24937. }
  24938. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24939. return null;
  24940. }
  24941. var texture = BABYLON.SerializationHelper.Parse(function () {
  24942. var generateMipMaps = true;
  24943. if (parsedTexture.noMipmap) {
  24944. generateMipMaps = false;
  24945. }
  24946. if (parsedTexture.mirrorPlane) {
  24947. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24948. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24949. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24950. return mirrorTexture;
  24951. }
  24952. else if (parsedTexture.isRenderTarget) {
  24953. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24954. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24955. return renderTargetTexture;
  24956. }
  24957. else {
  24958. var texture;
  24959. if (parsedTexture.base64String) {
  24960. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24961. }
  24962. else {
  24963. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24964. }
  24965. return texture;
  24966. }
  24967. }, parsedTexture, scene);
  24968. // Update Sampling Mode
  24969. if (parsedTexture.samplingMode) {
  24970. var sampling = parsedTexture.samplingMode;
  24971. if (texture._samplingMode !== sampling) {
  24972. texture.updateSamplingMode(sampling);
  24973. }
  24974. }
  24975. // Animations
  24976. if (parsedTexture.animations) {
  24977. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24978. var parsedAnimation = parsedTexture.animations[animationIndex];
  24979. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24980. }
  24981. }
  24982. return texture;
  24983. };
  24984. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24985. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24986. if (noMipmap === void 0) { noMipmap = false; }
  24987. if (invertY === void 0) { invertY = true; }
  24988. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24989. if (onLoad === void 0) { onLoad = null; }
  24990. if (onError === void 0) { onError = null; }
  24991. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24992. if (name.substr(0, 5) !== "data:") {
  24993. name = "data:" + name;
  24994. }
  24995. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24996. };
  24997. // Constants
  24998. Texture.NEAREST_SAMPLINGMODE = 1;
  24999. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25000. Texture.BILINEAR_SAMPLINGMODE = 2;
  25001. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25002. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25003. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25004. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25005. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25006. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25007. Texture.NEAREST_LINEAR = 7;
  25008. Texture.NEAREST_NEAREST = 8;
  25009. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25010. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25011. Texture.LINEAR_LINEAR = 11;
  25012. Texture.LINEAR_NEAREST = 12;
  25013. Texture.EXPLICIT_MODE = 0;
  25014. Texture.SPHERICAL_MODE = 1;
  25015. Texture.PLANAR_MODE = 2;
  25016. Texture.CUBIC_MODE = 3;
  25017. Texture.PROJECTION_MODE = 4;
  25018. Texture.SKYBOX_MODE = 5;
  25019. Texture.INVCUBIC_MODE = 6;
  25020. Texture.EQUIRECTANGULAR_MODE = 7;
  25021. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25022. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25023. Texture.CLAMP_ADDRESSMODE = 0;
  25024. Texture.WRAP_ADDRESSMODE = 1;
  25025. Texture.MIRROR_ADDRESSMODE = 2;
  25026. __decorate([
  25027. BABYLON.serialize()
  25028. ], Texture.prototype, "url", void 0);
  25029. __decorate([
  25030. BABYLON.serialize()
  25031. ], Texture.prototype, "uOffset", void 0);
  25032. __decorate([
  25033. BABYLON.serialize()
  25034. ], Texture.prototype, "vOffset", void 0);
  25035. __decorate([
  25036. BABYLON.serialize()
  25037. ], Texture.prototype, "uScale", void 0);
  25038. __decorate([
  25039. BABYLON.serialize()
  25040. ], Texture.prototype, "vScale", void 0);
  25041. __decorate([
  25042. BABYLON.serialize()
  25043. ], Texture.prototype, "uAng", void 0);
  25044. __decorate([
  25045. BABYLON.serialize()
  25046. ], Texture.prototype, "vAng", void 0);
  25047. __decorate([
  25048. BABYLON.serialize()
  25049. ], Texture.prototype, "wAng", void 0);
  25050. __decorate([
  25051. BABYLON.serialize()
  25052. ], Texture.prototype, "isBlocking", null);
  25053. return Texture;
  25054. }(BABYLON.BaseTexture));
  25055. BABYLON.Texture = Texture;
  25056. })(BABYLON || (BABYLON = {}));
  25057. //# sourceMappingURL=babylon.texture.js.map
  25058. var BABYLON;
  25059. (function (BABYLON) {
  25060. var _InstancesBatch = /** @class */ (function () {
  25061. function _InstancesBatch() {
  25062. this.mustReturn = false;
  25063. this.visibleInstances = new Array();
  25064. this.renderSelf = new Array();
  25065. }
  25066. return _InstancesBatch;
  25067. }());
  25068. BABYLON._InstancesBatch = _InstancesBatch;
  25069. var Mesh = /** @class */ (function (_super) {
  25070. __extends(Mesh, _super);
  25071. /**
  25072. * @constructor
  25073. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25074. * @param {Scene} scene The scene to add this mesh to.
  25075. * @param {Node} parent The parent of this mesh, if it has one
  25076. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25077. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25078. * When false, achieved by calling a clone(), also passing False.
  25079. * This will make creation of children, recursive.
  25080. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25081. */
  25082. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25083. if (scene === void 0) { scene = null; }
  25084. if (parent === void 0) { parent = null; }
  25085. if (source === void 0) { source = null; }
  25086. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25087. var _this = _super.call(this, name, scene) || this;
  25088. // Events
  25089. /**
  25090. * An event triggered before rendering the mesh
  25091. * @type {BABYLON.Observable}
  25092. */
  25093. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25094. /**
  25095. * An event triggered after rendering the mesh
  25096. * @type {BABYLON.Observable}
  25097. */
  25098. _this.onAfterRenderObservable = new BABYLON.Observable();
  25099. /**
  25100. * An event triggered before drawing the mesh
  25101. * @type {BABYLON.Observable}
  25102. */
  25103. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25104. // Members
  25105. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25106. _this.instances = new Array();
  25107. _this._LODLevels = new Array();
  25108. _this._visibleInstances = {};
  25109. _this._renderIdForInstances = new Array();
  25110. _this._batchCache = new _InstancesBatch();
  25111. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25112. // Use by builder only to know what orientation were the mesh build in.
  25113. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25114. _this.overrideMaterialSideOrientation = null;
  25115. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25116. // Will be used to save a source mesh reference, If any
  25117. _this._source = null;
  25118. scene = _this.getScene();
  25119. if (source) {
  25120. // Source mesh
  25121. _this._source = source;
  25122. // Geometry
  25123. if (source._geometry) {
  25124. source._geometry.applyToMesh(_this);
  25125. }
  25126. // Deep copy
  25127. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25128. // Metadata
  25129. if (source.metadata && source.metadata.clone) {
  25130. _this.metadata = source.metadata.clone();
  25131. }
  25132. else {
  25133. _this.metadata = source.metadata;
  25134. }
  25135. // Tags
  25136. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25137. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25138. }
  25139. // Parent
  25140. _this.parent = source.parent;
  25141. // Pivot
  25142. _this.setPivotMatrix(source.getPivotMatrix());
  25143. _this.id = name + "." + source.id;
  25144. // Material
  25145. _this.material = source.material;
  25146. var index;
  25147. if (!doNotCloneChildren) {
  25148. // Children
  25149. var directDescendants = source.getDescendants(true);
  25150. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25151. var child = directDescendants[index_1];
  25152. if (child.clone) {
  25153. child.clone(name + "." + child.name, _this);
  25154. }
  25155. }
  25156. }
  25157. // Physics clone
  25158. var physicsEngine = _this.getScene().getPhysicsEngine();
  25159. if (clonePhysicsImpostor && physicsEngine) {
  25160. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25161. if (impostor) {
  25162. _this.physicsImpostor = impostor.clone(_this);
  25163. }
  25164. }
  25165. // Particles
  25166. for (index = 0; index < scene.particleSystems.length; index++) {
  25167. var system = scene.particleSystems[index];
  25168. if (system.emitter === source) {
  25169. system.clone(system.name, _this);
  25170. }
  25171. }
  25172. _this.computeWorldMatrix(true);
  25173. }
  25174. // Parent
  25175. if (parent !== null) {
  25176. _this.parent = parent;
  25177. }
  25178. return _this;
  25179. }
  25180. Object.defineProperty(Mesh, "FRONTSIDE", {
  25181. /**
  25182. * Mesh side orientation : usually the external or front surface
  25183. */
  25184. get: function () {
  25185. return Mesh._FRONTSIDE;
  25186. },
  25187. enumerable: true,
  25188. configurable: true
  25189. });
  25190. Object.defineProperty(Mesh, "BACKSIDE", {
  25191. /**
  25192. * Mesh side orientation : usually the internal or back surface
  25193. */
  25194. get: function () {
  25195. return Mesh._BACKSIDE;
  25196. },
  25197. enumerable: true,
  25198. configurable: true
  25199. });
  25200. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25201. /**
  25202. * Mesh side orientation : both internal and external or front and back surfaces
  25203. */
  25204. get: function () {
  25205. return Mesh._DOUBLESIDE;
  25206. },
  25207. enumerable: true,
  25208. configurable: true
  25209. });
  25210. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25211. /**
  25212. * Mesh side orientation : by default, `FRONTSIDE`
  25213. */
  25214. get: function () {
  25215. return Mesh._DEFAULTSIDE;
  25216. },
  25217. enumerable: true,
  25218. configurable: true
  25219. });
  25220. Object.defineProperty(Mesh, "NO_CAP", {
  25221. /**
  25222. * Mesh cap setting : no cap
  25223. */
  25224. get: function () {
  25225. return Mesh._NO_CAP;
  25226. },
  25227. enumerable: true,
  25228. configurable: true
  25229. });
  25230. Object.defineProperty(Mesh, "CAP_START", {
  25231. /**
  25232. * Mesh cap setting : one cap at the beginning of the mesh
  25233. */
  25234. get: function () {
  25235. return Mesh._CAP_START;
  25236. },
  25237. enumerable: true,
  25238. configurable: true
  25239. });
  25240. Object.defineProperty(Mesh, "CAP_END", {
  25241. /**
  25242. * Mesh cap setting : one cap at the end of the mesh
  25243. */
  25244. get: function () {
  25245. return Mesh._CAP_END;
  25246. },
  25247. enumerable: true,
  25248. configurable: true
  25249. });
  25250. Object.defineProperty(Mesh, "CAP_ALL", {
  25251. /**
  25252. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25253. */
  25254. get: function () {
  25255. return Mesh._CAP_ALL;
  25256. },
  25257. enumerable: true,
  25258. configurable: true
  25259. });
  25260. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25261. set: function (callback) {
  25262. if (this._onBeforeDrawObserver) {
  25263. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25264. }
  25265. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25266. },
  25267. enumerable: true,
  25268. configurable: true
  25269. });
  25270. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25271. get: function () {
  25272. return this._morphTargetManager;
  25273. },
  25274. set: function (value) {
  25275. if (this._morphTargetManager === value) {
  25276. return;
  25277. }
  25278. this._morphTargetManager = value;
  25279. this._syncGeometryWithMorphTargetManager();
  25280. },
  25281. enumerable: true,
  25282. configurable: true
  25283. });
  25284. Object.defineProperty(Mesh.prototype, "source", {
  25285. get: function () {
  25286. return this._source;
  25287. },
  25288. enumerable: true,
  25289. configurable: true
  25290. });
  25291. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25292. get: function () {
  25293. return this._unIndexed;
  25294. },
  25295. set: function (value) {
  25296. if (this._unIndexed !== value) {
  25297. this._unIndexed = value;
  25298. this._markSubMeshesAsAttributesDirty();
  25299. }
  25300. },
  25301. enumerable: true,
  25302. configurable: true
  25303. });
  25304. // Methods
  25305. /**
  25306. * Returns the string "Mesh".
  25307. */
  25308. Mesh.prototype.getClassName = function () {
  25309. return "Mesh";
  25310. };
  25311. /**
  25312. * Returns a string.
  25313. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25314. */
  25315. Mesh.prototype.toString = function (fullDetails) {
  25316. var ret = _super.prototype.toString.call(this, fullDetails);
  25317. ret += ", n vertices: " + this.getTotalVertices();
  25318. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25319. if (this.animations) {
  25320. for (var i = 0; i < this.animations.length; i++) {
  25321. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25322. }
  25323. }
  25324. if (fullDetails) {
  25325. if (this._geometry) {
  25326. var ib = this.getIndices();
  25327. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25328. if (vb && ib) {
  25329. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25330. }
  25331. }
  25332. else {
  25333. ret += ", flat shading: UNKNOWN";
  25334. }
  25335. }
  25336. return ret;
  25337. };
  25338. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25339. /**
  25340. * True if the mesh has some Levels Of Details (LOD).
  25341. * Returns a boolean.
  25342. */
  25343. get: function () {
  25344. return this._LODLevels.length > 0;
  25345. },
  25346. enumerable: true,
  25347. configurable: true
  25348. });
  25349. /**
  25350. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25351. * @returns an array of {BABYLON.MeshLODLevel}
  25352. */
  25353. Mesh.prototype.getLODLevels = function () {
  25354. return this._LODLevels;
  25355. };
  25356. Mesh.prototype._sortLODLevels = function () {
  25357. this._LODLevels.sort(function (a, b) {
  25358. if (a.distance < b.distance) {
  25359. return 1;
  25360. }
  25361. if (a.distance > b.distance) {
  25362. return -1;
  25363. }
  25364. return 0;
  25365. });
  25366. };
  25367. /**
  25368. * Add a mesh as LOD level triggered at the given distance.
  25369. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25370. * @param {number} distance The distance from the center of the object to show this level
  25371. * @param {Mesh} mesh The mesh to be added as LOD level
  25372. * @return {Mesh} This mesh (for chaining)
  25373. */
  25374. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25375. if (mesh && mesh._masterMesh) {
  25376. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25377. return this;
  25378. }
  25379. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25380. this._LODLevels.push(level);
  25381. if (mesh) {
  25382. mesh._masterMesh = this;
  25383. }
  25384. this._sortLODLevels();
  25385. return this;
  25386. };
  25387. /**
  25388. * Returns the LOD level mesh at the passed distance or null if not found.
  25389. * It is related to the method `addLODLevel(distance, mesh)`.
  25390. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25391. * Returns an object Mesh or `null`.
  25392. */
  25393. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25394. for (var index = 0; index < this._LODLevels.length; index++) {
  25395. var level = this._LODLevels[index];
  25396. if (level.distance === distance) {
  25397. return level.mesh;
  25398. }
  25399. }
  25400. return null;
  25401. };
  25402. /**
  25403. * Remove a mesh from the LOD array
  25404. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25405. * @param {Mesh} mesh The mesh to be removed.
  25406. * @return {Mesh} This mesh (for chaining)
  25407. */
  25408. Mesh.prototype.removeLODLevel = function (mesh) {
  25409. for (var index = 0; index < this._LODLevels.length; index++) {
  25410. if (this._LODLevels[index].mesh === mesh) {
  25411. this._LODLevels.splice(index, 1);
  25412. if (mesh) {
  25413. mesh._masterMesh = null;
  25414. }
  25415. }
  25416. }
  25417. this._sortLODLevels();
  25418. return this;
  25419. };
  25420. /**
  25421. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25422. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25423. */
  25424. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25425. if (!this._LODLevels || this._LODLevels.length === 0) {
  25426. return this;
  25427. }
  25428. var bSphere;
  25429. if (boundingSphere) {
  25430. bSphere = boundingSphere;
  25431. }
  25432. else {
  25433. var boundingInfo = this.getBoundingInfo();
  25434. bSphere = boundingInfo.boundingSphere;
  25435. }
  25436. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25437. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25438. if (this.onLODLevelSelection) {
  25439. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25440. }
  25441. return this;
  25442. }
  25443. for (var index = 0; index < this._LODLevels.length; index++) {
  25444. var level = this._LODLevels[index];
  25445. if (level.distance < distanceToCamera) {
  25446. if (level.mesh) {
  25447. level.mesh._preActivate();
  25448. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25449. }
  25450. if (this.onLODLevelSelection) {
  25451. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25452. }
  25453. return level.mesh;
  25454. }
  25455. }
  25456. if (this.onLODLevelSelection) {
  25457. this.onLODLevelSelection(distanceToCamera, this, this);
  25458. }
  25459. return this;
  25460. };
  25461. Object.defineProperty(Mesh.prototype, "geometry", {
  25462. /**
  25463. * Returns the mesh internal Geometry object.
  25464. */
  25465. get: function () {
  25466. return this._geometry;
  25467. },
  25468. enumerable: true,
  25469. configurable: true
  25470. });
  25471. /**
  25472. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25473. */
  25474. Mesh.prototype.getTotalVertices = function () {
  25475. if (this._geometry === null || this._geometry === undefined) {
  25476. return 0;
  25477. }
  25478. return this._geometry.getTotalVertices();
  25479. };
  25480. /**
  25481. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25482. * 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.
  25483. * You can force the copy with forceCopy === true
  25484. * Returns null if the mesh has no geometry or no vertex buffer.
  25485. * Possible `kind` values :
  25486. * - BABYLON.VertexBuffer.PositionKind
  25487. * - BABYLON.VertexBuffer.UVKind
  25488. * - BABYLON.VertexBuffer.UV2Kind
  25489. * - BABYLON.VertexBuffer.UV3Kind
  25490. * - BABYLON.VertexBuffer.UV4Kind
  25491. * - BABYLON.VertexBuffer.UV5Kind
  25492. * - BABYLON.VertexBuffer.UV6Kind
  25493. * - BABYLON.VertexBuffer.ColorKind
  25494. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25495. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25496. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25497. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25498. */
  25499. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25500. if (!this._geometry) {
  25501. return null;
  25502. }
  25503. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25504. };
  25505. /**
  25506. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25507. * Returns `null` if the mesh has no geometry.
  25508. * Possible `kind` values :
  25509. * - BABYLON.VertexBuffer.PositionKind
  25510. * - BABYLON.VertexBuffer.UVKind
  25511. * - BABYLON.VertexBuffer.UV2Kind
  25512. * - BABYLON.VertexBuffer.UV3Kind
  25513. * - BABYLON.VertexBuffer.UV4Kind
  25514. * - BABYLON.VertexBuffer.UV5Kind
  25515. * - BABYLON.VertexBuffer.UV6Kind
  25516. * - BABYLON.VertexBuffer.ColorKind
  25517. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25518. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25519. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25520. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25521. */
  25522. Mesh.prototype.getVertexBuffer = function (kind) {
  25523. if (!this._geometry) {
  25524. return null;
  25525. }
  25526. return this._geometry.getVertexBuffer(kind);
  25527. };
  25528. /**
  25529. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25530. * Possible `kind` values :
  25531. * - BABYLON.VertexBuffer.PositionKind
  25532. * - BABYLON.VertexBuffer.UVKind
  25533. * - BABYLON.VertexBuffer.UV2Kind
  25534. * - BABYLON.VertexBuffer.UV3Kind
  25535. * - BABYLON.VertexBuffer.UV4Kind
  25536. * - BABYLON.VertexBuffer.UV5Kind
  25537. * - BABYLON.VertexBuffer.UV6Kind
  25538. * - BABYLON.VertexBuffer.ColorKind
  25539. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25540. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25541. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25542. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25543. */
  25544. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25545. if (!this._geometry) {
  25546. if (this._delayInfo) {
  25547. return this._delayInfo.indexOf(kind) !== -1;
  25548. }
  25549. return false;
  25550. }
  25551. return this._geometry.isVerticesDataPresent(kind);
  25552. };
  25553. /**
  25554. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25555. * Possible `kind` values :
  25556. * - BABYLON.VertexBuffer.PositionKind
  25557. * - BABYLON.VertexBuffer.UVKind
  25558. * - BABYLON.VertexBuffer.UV2Kind
  25559. * - BABYLON.VertexBuffer.UV3Kind
  25560. * - BABYLON.VertexBuffer.UV4Kind
  25561. * - BABYLON.VertexBuffer.UV5Kind
  25562. * - BABYLON.VertexBuffer.UV6Kind
  25563. * - BABYLON.VertexBuffer.ColorKind
  25564. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25565. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25566. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25567. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25568. */
  25569. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25570. if (!this._geometry) {
  25571. if (this._delayInfo) {
  25572. return this._delayInfo.indexOf(kind) !== -1;
  25573. }
  25574. return false;
  25575. }
  25576. return this._geometry.isVertexBufferUpdatable(kind);
  25577. };
  25578. /**
  25579. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25580. * Possible `kind` values :
  25581. * - BABYLON.VertexBuffer.PositionKind
  25582. * - BABYLON.VertexBuffer.UVKind
  25583. * - BABYLON.VertexBuffer.UV2Kind
  25584. * - BABYLON.VertexBuffer.UV3Kind
  25585. * - BABYLON.VertexBuffer.UV4Kind
  25586. * - BABYLON.VertexBuffer.UV5Kind
  25587. * - BABYLON.VertexBuffer.UV6Kind
  25588. * - BABYLON.VertexBuffer.ColorKind
  25589. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25590. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25591. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25592. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25593. */
  25594. Mesh.prototype.getVerticesDataKinds = function () {
  25595. if (!this._geometry) {
  25596. var result = new Array();
  25597. if (this._delayInfo) {
  25598. this._delayInfo.forEach(function (kind, index, array) {
  25599. result.push(kind);
  25600. });
  25601. }
  25602. return result;
  25603. }
  25604. return this._geometry.getVerticesDataKinds();
  25605. };
  25606. /**
  25607. * Returns a positive integer : the total number of indices in this mesh geometry.
  25608. * Returns zero if the mesh has no geometry.
  25609. */
  25610. Mesh.prototype.getTotalIndices = function () {
  25611. if (!this._geometry) {
  25612. return 0;
  25613. }
  25614. return this._geometry.getTotalIndices();
  25615. };
  25616. /**
  25617. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25618. * 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.
  25619. * Returns an empty array if the mesh has no geometry.
  25620. */
  25621. Mesh.prototype.getIndices = function (copyWhenShared) {
  25622. if (!this._geometry) {
  25623. return [];
  25624. }
  25625. return this._geometry.getIndices(copyWhenShared);
  25626. };
  25627. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25628. get: function () {
  25629. return this._masterMesh !== null && this._masterMesh !== undefined;
  25630. },
  25631. enumerable: true,
  25632. configurable: true
  25633. });
  25634. /**
  25635. * Determine if the current mesh is ready to be rendered
  25636. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25637. * @returns true if all associated assets are ready (material, textures, shaders)
  25638. */
  25639. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25640. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25641. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25642. return false;
  25643. }
  25644. if (!_super.prototype.isReady.call(this)) {
  25645. return false;
  25646. }
  25647. if (!this.subMeshes || this.subMeshes.length === 0) {
  25648. return true;
  25649. }
  25650. var engine = this.getEngine();
  25651. var scene = this.getScene();
  25652. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25653. this.computeWorldMatrix();
  25654. var mat = this.material || scene.defaultMaterial;
  25655. if (mat) {
  25656. if (mat.storeEffectOnSubMeshes) {
  25657. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25658. var subMesh = _a[_i];
  25659. var effectiveMaterial = subMesh.getMaterial();
  25660. if (effectiveMaterial) {
  25661. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25662. return false;
  25663. }
  25664. }
  25665. }
  25666. }
  25667. else {
  25668. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25669. return false;
  25670. }
  25671. }
  25672. }
  25673. // Shadows
  25674. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25675. var light = _c[_b];
  25676. var generator = light.getShadowGenerator();
  25677. if (generator) {
  25678. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25679. var subMesh = _e[_d];
  25680. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25681. return false;
  25682. }
  25683. }
  25684. }
  25685. }
  25686. // LOD
  25687. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25688. var lod = _g[_f];
  25689. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25690. return false;
  25691. }
  25692. }
  25693. return true;
  25694. };
  25695. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25696. /**
  25697. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25698. * This property is pertinent only for updatable parametric shapes.
  25699. */
  25700. get: function () {
  25701. return this._areNormalsFrozen;
  25702. },
  25703. enumerable: true,
  25704. configurable: true
  25705. });
  25706. /**
  25707. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25708. * It has no effect at all on other shapes.
  25709. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25710. * Returns the Mesh.
  25711. */
  25712. Mesh.prototype.freezeNormals = function () {
  25713. this._areNormalsFrozen = true;
  25714. return this;
  25715. };
  25716. /**
  25717. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25718. * It has no effect at all on other shapes.
  25719. * It reactivates the mesh normals computation if it was previously frozen.
  25720. * Returns the Mesh.
  25721. */
  25722. Mesh.prototype.unfreezeNormals = function () {
  25723. this._areNormalsFrozen = false;
  25724. return this;
  25725. };
  25726. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25727. /**
  25728. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25729. */
  25730. set: function (count) {
  25731. this._overridenInstanceCount = count;
  25732. },
  25733. enumerable: true,
  25734. configurable: true
  25735. });
  25736. // Methods
  25737. Mesh.prototype._preActivate = function () {
  25738. var sceneRenderId = this.getScene().getRenderId();
  25739. if (this._preActivateId === sceneRenderId) {
  25740. return this;
  25741. }
  25742. this._preActivateId = sceneRenderId;
  25743. this._visibleInstances = null;
  25744. return this;
  25745. };
  25746. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25747. if (this._visibleInstances) {
  25748. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25749. }
  25750. return this;
  25751. };
  25752. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25753. if (!this._visibleInstances) {
  25754. this._visibleInstances = {};
  25755. this._visibleInstances.defaultRenderId = renderId;
  25756. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25757. }
  25758. if (!this._visibleInstances[renderId]) {
  25759. this._visibleInstances[renderId] = new Array();
  25760. }
  25761. this._visibleInstances[renderId].push(instance);
  25762. return this;
  25763. };
  25764. /**
  25765. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25766. * This means the mesh underlying bounding box and sphere are recomputed.
  25767. * Returns the Mesh.
  25768. */
  25769. Mesh.prototype.refreshBoundingInfo = function () {
  25770. return this._refreshBoundingInfo(false);
  25771. };
  25772. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25773. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25774. return this;
  25775. }
  25776. var data = this._getPositionData(applySkeleton);
  25777. if (data) {
  25778. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25779. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25780. }
  25781. if (this.subMeshes) {
  25782. for (var index = 0; index < this.subMeshes.length; index++) {
  25783. this.subMeshes[index].refreshBoundingInfo();
  25784. }
  25785. }
  25786. this._updateBoundingInfo();
  25787. return this;
  25788. };
  25789. Mesh.prototype._getPositionData = function (applySkeleton) {
  25790. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25791. if (data && applySkeleton && this.skeleton) {
  25792. data = BABYLON.Tools.Slice(data);
  25793. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25794. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25795. if (matricesWeightsData && matricesIndicesData) {
  25796. var needExtras = this.numBoneInfluencers > 4;
  25797. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25798. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25799. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25800. var tempVector = BABYLON.Tmp.Vector3[0];
  25801. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25802. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25803. var matWeightIdx = 0;
  25804. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25805. finalMatrix.reset();
  25806. var inf;
  25807. var weight;
  25808. for (inf = 0; inf < 4; inf++) {
  25809. weight = matricesWeightsData[matWeightIdx + inf];
  25810. if (weight <= 0)
  25811. break;
  25812. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25813. finalMatrix.addToSelf(tempMatrix);
  25814. }
  25815. if (needExtras) {
  25816. for (inf = 0; inf < 4; inf++) {
  25817. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25818. if (weight <= 0)
  25819. break;
  25820. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25821. finalMatrix.addToSelf(tempMatrix);
  25822. }
  25823. }
  25824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25825. tempVector.toArray(data, index);
  25826. }
  25827. }
  25828. }
  25829. return data;
  25830. };
  25831. Mesh.prototype._createGlobalSubMesh = function (force) {
  25832. var totalVertices = this.getTotalVertices();
  25833. if (!totalVertices || !this.getIndices()) {
  25834. return null;
  25835. }
  25836. // Check if we need to recreate the submeshes
  25837. if (this.subMeshes && this.subMeshes.length > 0) {
  25838. var ib = this.getIndices();
  25839. if (!ib) {
  25840. return null;
  25841. }
  25842. var totalIndices = ib.length;
  25843. var needToRecreate = false;
  25844. if (force) {
  25845. needToRecreate = true;
  25846. }
  25847. else {
  25848. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25849. var submesh = _a[_i];
  25850. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25851. needToRecreate = true;
  25852. break;
  25853. }
  25854. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25855. needToRecreate = true;
  25856. break;
  25857. }
  25858. }
  25859. }
  25860. if (!needToRecreate) {
  25861. return this.subMeshes[0];
  25862. }
  25863. }
  25864. this.releaseSubMeshes();
  25865. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25866. };
  25867. Mesh.prototype.subdivide = function (count) {
  25868. if (count < 1) {
  25869. return;
  25870. }
  25871. var totalIndices = this.getTotalIndices();
  25872. var subdivisionSize = (totalIndices / count) | 0;
  25873. var offset = 0;
  25874. // Ensure that subdivisionSize is a multiple of 3
  25875. while (subdivisionSize % 3 !== 0) {
  25876. subdivisionSize++;
  25877. }
  25878. this.releaseSubMeshes();
  25879. for (var index = 0; index < count; index++) {
  25880. if (offset >= totalIndices) {
  25881. break;
  25882. }
  25883. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25884. offset += subdivisionSize;
  25885. }
  25886. this.synchronizeInstances();
  25887. };
  25888. /**
  25889. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25890. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25891. * The `data` are either a numeric array either a Float32Array.
  25892. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25893. * 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).
  25894. * Note that a new underlying VertexBuffer object is created each call.
  25895. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25896. *
  25897. * Possible `kind` values :
  25898. * - BABYLON.VertexBuffer.PositionKind
  25899. * - BABYLON.VertexBuffer.UVKind
  25900. * - BABYLON.VertexBuffer.UV2Kind
  25901. * - BABYLON.VertexBuffer.UV3Kind
  25902. * - BABYLON.VertexBuffer.UV4Kind
  25903. * - BABYLON.VertexBuffer.UV5Kind
  25904. * - BABYLON.VertexBuffer.UV6Kind
  25905. * - BABYLON.VertexBuffer.ColorKind
  25906. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25907. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25908. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25909. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25910. *
  25911. * Returns the Mesh.
  25912. */
  25913. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25914. if (updatable === void 0) { updatable = false; }
  25915. if (!this._geometry) {
  25916. var vertexData = new BABYLON.VertexData();
  25917. vertexData.set(data, kind);
  25918. var scene = this.getScene();
  25919. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25920. }
  25921. else {
  25922. this._geometry.setVerticesData(kind, data, updatable, stride);
  25923. }
  25924. return this;
  25925. };
  25926. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25927. if (updatable === void 0) { updatable = true; }
  25928. var vb = this.getVertexBuffer(kind);
  25929. if (!vb || vb.isUpdatable() === updatable) {
  25930. return;
  25931. }
  25932. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25933. };
  25934. /**
  25935. * Sets the mesh VertexBuffer.
  25936. * Returns the Mesh.
  25937. */
  25938. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25939. if (!this._geometry) {
  25940. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25941. }
  25942. this._geometry.setVerticesBuffer(buffer);
  25943. return this;
  25944. };
  25945. /**
  25946. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25947. * If the mesh has no geometry, it is simply returned as it is.
  25948. * The `data` are either a numeric array either a Float32Array.
  25949. * No new underlying VertexBuffer object is created.
  25950. * 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.
  25951. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25952. *
  25953. * Possible `kind` values :
  25954. * - BABYLON.VertexBuffer.PositionKind
  25955. * - BABYLON.VertexBuffer.UVKind
  25956. * - BABYLON.VertexBuffer.UV2Kind
  25957. * - BABYLON.VertexBuffer.UV3Kind
  25958. * - BABYLON.VertexBuffer.UV4Kind
  25959. * - BABYLON.VertexBuffer.UV5Kind
  25960. * - BABYLON.VertexBuffer.UV6Kind
  25961. * - BABYLON.VertexBuffer.ColorKind
  25962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25966. *
  25967. * Returns the Mesh.
  25968. */
  25969. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25970. if (!this._geometry) {
  25971. return this;
  25972. }
  25973. if (!makeItUnique) {
  25974. this._geometry.updateVerticesData(kind, data, updateExtends);
  25975. }
  25976. else {
  25977. this.makeGeometryUnique();
  25978. this.updateVerticesData(kind, data, updateExtends, false);
  25979. }
  25980. return this;
  25981. };
  25982. /**
  25983. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25984. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25985. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25986. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25987. * Returns the Mesh.
  25988. */
  25989. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25990. if (computeNormals === void 0) { computeNormals = true; }
  25991. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25992. if (!positions) {
  25993. return this;
  25994. }
  25995. positionFunction(positions);
  25996. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25997. if (computeNormals) {
  25998. var indices = this.getIndices();
  25999. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26000. if (!normals) {
  26001. return this;
  26002. }
  26003. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26004. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26005. }
  26006. return this;
  26007. };
  26008. /**
  26009. * Creates a un-shared specific occurence of the geometry for the mesh.
  26010. * Returns the Mesh.
  26011. */
  26012. Mesh.prototype.makeGeometryUnique = function () {
  26013. if (!this._geometry) {
  26014. return this;
  26015. }
  26016. var oldGeometry = this._geometry;
  26017. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26018. oldGeometry.releaseForMesh(this, true);
  26019. geometry.applyToMesh(this);
  26020. return this;
  26021. };
  26022. /**
  26023. * Sets the mesh indices.
  26024. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26025. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26026. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26027. * This method creates a new index buffer each call.
  26028. * Returns the Mesh.
  26029. */
  26030. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26031. if (totalVertices === void 0) { totalVertices = null; }
  26032. if (updatable === void 0) { updatable = false; }
  26033. if (!this._geometry) {
  26034. var vertexData = new BABYLON.VertexData();
  26035. vertexData.indices = indices;
  26036. var scene = this.getScene();
  26037. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26038. }
  26039. else {
  26040. this._geometry.setIndices(indices, totalVertices, updatable);
  26041. }
  26042. return this;
  26043. };
  26044. /**
  26045. * Update the current index buffer
  26046. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26047. * Returns the Mesh.
  26048. */
  26049. Mesh.prototype.updateIndices = function (indices, offset) {
  26050. if (!this._geometry) {
  26051. return this;
  26052. }
  26053. this._geometry.updateIndices(indices, offset);
  26054. return this;
  26055. };
  26056. /**
  26057. * Invert the geometry to move from a right handed system to a left handed one.
  26058. * Returns the Mesh.
  26059. */
  26060. Mesh.prototype.toLeftHanded = function () {
  26061. if (!this._geometry) {
  26062. return this;
  26063. }
  26064. this._geometry.toLeftHanded();
  26065. return this;
  26066. };
  26067. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26068. if (!this._geometry) {
  26069. return this;
  26070. }
  26071. var engine = this.getScene().getEngine();
  26072. // Wireframe
  26073. var indexToBind;
  26074. if (this._unIndexed) {
  26075. indexToBind = null;
  26076. }
  26077. else {
  26078. switch (fillMode) {
  26079. case BABYLON.Material.PointFillMode:
  26080. indexToBind = null;
  26081. break;
  26082. case BABYLON.Material.WireFrameFillMode:
  26083. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26084. break;
  26085. default:
  26086. case BABYLON.Material.TriangleFillMode:
  26087. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26088. break;
  26089. }
  26090. }
  26091. // VBOs
  26092. this._geometry._bind(effect, indexToBind);
  26093. return this;
  26094. };
  26095. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26096. if (alternate === void 0) { alternate = false; }
  26097. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26098. return this;
  26099. }
  26100. this.onBeforeDrawObservable.notifyObservers(this);
  26101. var scene = this.getScene();
  26102. var engine = scene.getEngine();
  26103. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26104. // or triangles as points
  26105. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26106. }
  26107. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26108. // Triangles as wireframe
  26109. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26110. }
  26111. else {
  26112. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26113. }
  26114. if (scene._isAlternateRenderingEnabled && !alternate) {
  26115. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26116. if (!effect || !scene.activeCamera) {
  26117. return this;
  26118. }
  26119. scene._switchToAlternateCameraConfiguration(true);
  26120. this._effectiveMaterial.bindView(effect);
  26121. this._effectiveMaterial.bindViewProjection(effect);
  26122. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26123. this._draw(subMesh, fillMode, instancesCount, true);
  26124. engine.setViewport(scene.activeCamera.viewport);
  26125. scene._switchToAlternateCameraConfiguration(false);
  26126. this._effectiveMaterial.bindView(effect);
  26127. this._effectiveMaterial.bindViewProjection(effect);
  26128. }
  26129. return this;
  26130. };
  26131. /**
  26132. * Registers for this mesh a javascript function called just before the rendering process.
  26133. * This function is passed the current mesh.
  26134. * Return the Mesh.
  26135. */
  26136. Mesh.prototype.registerBeforeRender = function (func) {
  26137. this.onBeforeRenderObservable.add(func);
  26138. return this;
  26139. };
  26140. /**
  26141. * Disposes a previously registered javascript function called before the rendering.
  26142. * This function is passed the current mesh.
  26143. * Returns the Mesh.
  26144. */
  26145. Mesh.prototype.unregisterBeforeRender = function (func) {
  26146. this.onBeforeRenderObservable.removeCallback(func);
  26147. return this;
  26148. };
  26149. /**
  26150. * Registers for this mesh a javascript function called just after the rendering is complete.
  26151. * This function is passed the current mesh.
  26152. * Returns the Mesh.
  26153. */
  26154. Mesh.prototype.registerAfterRender = function (func) {
  26155. this.onAfterRenderObservable.add(func);
  26156. return this;
  26157. };
  26158. /**
  26159. * Disposes a previously registered javascript function called after the rendering.
  26160. * This function is passed the current mesh.
  26161. * Return the Mesh.
  26162. */
  26163. Mesh.prototype.unregisterAfterRender = function (func) {
  26164. this.onAfterRenderObservable.removeCallback(func);
  26165. return this;
  26166. };
  26167. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26168. var scene = this.getScene();
  26169. this._batchCache.mustReturn = false;
  26170. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26171. this._batchCache.visibleInstances[subMeshId] = null;
  26172. if (this._visibleInstances) {
  26173. var currentRenderId = scene.getRenderId();
  26174. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26175. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26176. var selfRenderId = this._renderId;
  26177. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26178. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26179. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26180. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26181. }
  26182. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26183. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26184. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26185. this._batchCache.mustReturn = true;
  26186. return this._batchCache;
  26187. }
  26188. if (currentRenderId !== selfRenderId) {
  26189. this._batchCache.renderSelf[subMeshId] = false;
  26190. }
  26191. }
  26192. this._renderIdForInstances[subMeshId] = currentRenderId;
  26193. }
  26194. return this._batchCache;
  26195. };
  26196. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26197. var visibleInstances = batch.visibleInstances[subMesh._id];
  26198. if (!visibleInstances) {
  26199. return this;
  26200. }
  26201. var matricesCount = visibleInstances.length + 1;
  26202. var bufferSize = matricesCount * 16 * 4;
  26203. var currentInstancesBufferSize = this._instancesBufferSize;
  26204. var instancesBuffer = this._instancesBuffer;
  26205. while (this._instancesBufferSize < bufferSize) {
  26206. this._instancesBufferSize *= 2;
  26207. }
  26208. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26209. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26210. }
  26211. var offset = 0;
  26212. var instancesCount = 0;
  26213. var world = this.getWorldMatrix();
  26214. if (batch.renderSelf[subMesh._id]) {
  26215. world.copyToArray(this._instancesData, offset);
  26216. offset += 16;
  26217. instancesCount++;
  26218. }
  26219. if (visibleInstances) {
  26220. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26221. var instance = visibleInstances[instanceIndex];
  26222. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26223. offset += 16;
  26224. instancesCount++;
  26225. }
  26226. }
  26227. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26228. if (instancesBuffer) {
  26229. instancesBuffer.dispose();
  26230. }
  26231. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26232. this._instancesBuffer = instancesBuffer;
  26233. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26234. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26235. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26236. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26237. }
  26238. else {
  26239. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26240. }
  26241. this._bind(subMesh, effect, fillMode);
  26242. this._draw(subMesh, fillMode, instancesCount);
  26243. engine.unbindInstanceAttributes();
  26244. return this;
  26245. };
  26246. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26247. var scene = this.getScene();
  26248. var engine = scene.getEngine();
  26249. if (hardwareInstancedRendering) {
  26250. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26251. }
  26252. else {
  26253. if (batch.renderSelf[subMesh._id]) {
  26254. // Draw
  26255. if (onBeforeDraw) {
  26256. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26257. }
  26258. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26259. }
  26260. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26261. if (visibleInstancesForSubMesh) {
  26262. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26263. var instance = visibleInstancesForSubMesh[instanceIndex];
  26264. // World
  26265. var world = instance.getWorldMatrix();
  26266. if (onBeforeDraw) {
  26267. onBeforeDraw(true, world, effectiveMaterial);
  26268. }
  26269. // Draw
  26270. this._draw(subMesh, fillMode);
  26271. }
  26272. }
  26273. }
  26274. return this;
  26275. };
  26276. /**
  26277. * Triggers the draw call for the mesh.
  26278. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26279. * Returns the Mesh.
  26280. */
  26281. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26282. this.checkOcclusionQuery();
  26283. if (this._isOccluded) {
  26284. return this;
  26285. }
  26286. var scene = this.getScene();
  26287. // Managing instances
  26288. var batch = this._getInstancesRenderList(subMesh._id);
  26289. if (batch.mustReturn) {
  26290. return this;
  26291. }
  26292. // Checking geometry state
  26293. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26294. return this;
  26295. }
  26296. this.onBeforeRenderObservable.notifyObservers(this);
  26297. var engine = scene.getEngine();
  26298. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26299. // Material
  26300. var material = subMesh.getMaterial();
  26301. if (!material) {
  26302. return this;
  26303. }
  26304. this._effectiveMaterial = material;
  26305. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26306. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26307. return this;
  26308. }
  26309. }
  26310. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26311. return this;
  26312. }
  26313. // Alpha mode
  26314. if (enableAlphaMode) {
  26315. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26316. }
  26317. // Outline - step 1
  26318. var savedDepthWrite = engine.getDepthWrite();
  26319. if (this.renderOutline) {
  26320. engine.setDepthWrite(false);
  26321. scene.getOutlineRenderer().render(subMesh, batch);
  26322. engine.setDepthWrite(savedDepthWrite);
  26323. }
  26324. var effect;
  26325. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26326. effect = subMesh.effect;
  26327. }
  26328. else {
  26329. effect = this._effectiveMaterial.getEffect();
  26330. }
  26331. if (!effect) {
  26332. return this;
  26333. }
  26334. var sideOrientation = this.overrideMaterialSideOrientation;
  26335. if (sideOrientation == null) {
  26336. sideOrientation = this._effectiveMaterial.sideOrientation;
  26337. if (this._getWorldMatrixDeterminant() < 0) {
  26338. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26339. }
  26340. }
  26341. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26342. if (this._effectiveMaterial.forceDepthWrite) {
  26343. engine.setDepthWrite(true);
  26344. }
  26345. // Bind
  26346. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26347. if (!hardwareInstancedRendering) {
  26348. this._bind(subMesh, effect, fillMode);
  26349. }
  26350. var world = this.getWorldMatrix();
  26351. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26352. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26353. }
  26354. else {
  26355. this._effectiveMaterial.bind(world, this);
  26356. }
  26357. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26358. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26359. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26360. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26361. }
  26362. // Draw
  26363. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26364. // Unbind
  26365. this._effectiveMaterial.unbind();
  26366. // Outline - step 2
  26367. if (this.renderOutline && savedDepthWrite) {
  26368. engine.setDepthWrite(true);
  26369. engine.setColorWrite(false);
  26370. scene.getOutlineRenderer().render(subMesh, batch);
  26371. engine.setColorWrite(true);
  26372. }
  26373. // Overlay
  26374. if (this.renderOverlay) {
  26375. var currentMode = engine.getAlphaMode();
  26376. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26377. scene.getOutlineRenderer().render(subMesh, batch, true);
  26378. engine.setAlphaMode(currentMode);
  26379. }
  26380. this.onAfterRenderObservable.notifyObservers(this);
  26381. return this;
  26382. };
  26383. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26384. if (isInstance && effectiveMaterial) {
  26385. effectiveMaterial.bindOnlyWorldMatrix(world);
  26386. }
  26387. };
  26388. /**
  26389. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26390. */
  26391. Mesh.prototype.getEmittedParticleSystems = function () {
  26392. var results = new Array();
  26393. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26394. var particleSystem = this.getScene().particleSystems[index];
  26395. if (particleSystem.emitter === this) {
  26396. results.push(particleSystem);
  26397. }
  26398. }
  26399. return results;
  26400. };
  26401. /**
  26402. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26403. */
  26404. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26405. var results = new Array();
  26406. var descendants = this.getDescendants();
  26407. descendants.push(this);
  26408. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26409. var particleSystem = this.getScene().particleSystems[index];
  26410. var emitter = particleSystem.emitter;
  26411. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26412. results.push(particleSystem);
  26413. }
  26414. }
  26415. return results;
  26416. };
  26417. Mesh.prototype._checkDelayState = function () {
  26418. var scene = this.getScene();
  26419. if (this._geometry) {
  26420. this._geometry.load(scene);
  26421. }
  26422. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26423. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26424. this._queueLoad(scene);
  26425. }
  26426. return this;
  26427. };
  26428. Mesh.prototype._queueLoad = function (scene) {
  26429. var _this = this;
  26430. scene._addPendingData(this);
  26431. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26432. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26433. if (data instanceof ArrayBuffer) {
  26434. _this._delayLoadingFunction(data, _this);
  26435. }
  26436. else {
  26437. _this._delayLoadingFunction(JSON.parse(data), _this);
  26438. }
  26439. _this.instances.forEach(function (instance) {
  26440. instance._syncSubMeshes();
  26441. });
  26442. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26443. scene._removePendingData(_this);
  26444. }, function () { }, scene.database, getBinaryData);
  26445. return this;
  26446. };
  26447. /**
  26448. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26449. */
  26450. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26451. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26452. return false;
  26453. }
  26454. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26455. return false;
  26456. }
  26457. this._checkDelayState();
  26458. return true;
  26459. };
  26460. /**
  26461. * Sets the mesh material by the material or multiMaterial `id` property.
  26462. * The material `id` is a string identifying the material or the multiMaterial.
  26463. * This method returns the Mesh.
  26464. */
  26465. Mesh.prototype.setMaterialByID = function (id) {
  26466. var materials = this.getScene().materials;
  26467. var index;
  26468. for (index = materials.length - 1; index > -1; index--) {
  26469. if (materials[index].id === id) {
  26470. this.material = materials[index];
  26471. return this;
  26472. }
  26473. }
  26474. // Multi
  26475. var multiMaterials = this.getScene().multiMaterials;
  26476. for (index = multiMaterials.length - 1; index > -1; index--) {
  26477. if (multiMaterials[index].id === id) {
  26478. this.material = multiMaterials[index];
  26479. return this;
  26480. }
  26481. }
  26482. return this;
  26483. };
  26484. /**
  26485. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26486. */
  26487. Mesh.prototype.getAnimatables = function () {
  26488. var results = new Array();
  26489. if (this.material) {
  26490. results.push(this.material);
  26491. }
  26492. if (this.skeleton) {
  26493. results.push(this.skeleton);
  26494. }
  26495. return results;
  26496. };
  26497. /**
  26498. * Modifies the mesh geometry according to the passed transformation matrix.
  26499. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26500. * The mesh normals are modified accordingly the same transformation.
  26501. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26502. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26503. * Returns the Mesh.
  26504. */
  26505. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26506. // Position
  26507. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26508. return this;
  26509. }
  26510. var submeshes = this.subMeshes.splice(0);
  26511. this._resetPointsArrayCache();
  26512. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26513. var temp = new Array();
  26514. var index;
  26515. for (index = 0; index < data.length; index += 3) {
  26516. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26517. }
  26518. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26519. // Normals
  26520. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26521. return this;
  26522. }
  26523. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26524. temp = [];
  26525. for (index = 0; index < data.length; index += 3) {
  26526. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26527. }
  26528. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26529. // flip faces?
  26530. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26531. this.flipFaces();
  26532. }
  26533. // Restore submeshes
  26534. this.releaseSubMeshes();
  26535. this.subMeshes = submeshes;
  26536. return this;
  26537. };
  26538. /**
  26539. * Modifies the mesh geometry according to its own current World Matrix.
  26540. * The mesh World Matrix is then reset.
  26541. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26542. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26543. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26544. * Returns the Mesh.
  26545. */
  26546. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26547. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26548. this.scaling.copyFromFloats(1, 1, 1);
  26549. this.position.copyFromFloats(0, 0, 0);
  26550. this.rotation.copyFromFloats(0, 0, 0);
  26551. //only if quaternion is already set
  26552. if (this.rotationQuaternion) {
  26553. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26554. }
  26555. this._worldMatrix = BABYLON.Matrix.Identity();
  26556. return this;
  26557. };
  26558. Object.defineProperty(Mesh.prototype, "_positions", {
  26559. // Cache
  26560. get: function () {
  26561. if (this._geometry) {
  26562. return this._geometry._positions;
  26563. }
  26564. return null;
  26565. },
  26566. enumerable: true,
  26567. configurable: true
  26568. });
  26569. Mesh.prototype._resetPointsArrayCache = function () {
  26570. if (this._geometry) {
  26571. this._geometry._resetPointsArrayCache();
  26572. }
  26573. return this;
  26574. };
  26575. Mesh.prototype._generatePointsArray = function () {
  26576. if (this._geometry) {
  26577. return this._geometry._generatePointsArray();
  26578. }
  26579. return false;
  26580. };
  26581. /**
  26582. * Returns a new Mesh object generated from the current mesh properties.
  26583. * This method must not get confused with createInstance().
  26584. * The parameter `name` is a string, the name given to the new mesh.
  26585. * The optional parameter `newParent` can be any Node object (default `null`).
  26586. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26587. * 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.
  26588. */
  26589. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26590. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26591. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26592. };
  26593. /**
  26594. * Disposes the Mesh.
  26595. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26596. * Returns nothing.
  26597. */
  26598. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26599. var _this = this;
  26600. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26601. this.morphTargetManager = null;
  26602. if (this._geometry) {
  26603. this._geometry.releaseForMesh(this, true);
  26604. }
  26605. // Sources
  26606. var meshes = this.getScene().meshes;
  26607. meshes.forEach(function (abstractMesh) {
  26608. var mesh = abstractMesh;
  26609. if (mesh._source && mesh._source === _this) {
  26610. mesh._source = null;
  26611. }
  26612. });
  26613. this._source = null;
  26614. // Instances
  26615. if (this._instancesBuffer) {
  26616. this._instancesBuffer.dispose();
  26617. this._instancesBuffer = null;
  26618. }
  26619. while (this.instances.length) {
  26620. this.instances[0].dispose();
  26621. }
  26622. // Highlight layers.
  26623. var highlightLayers = this.getScene().highlightLayers;
  26624. for (var i = 0; i < highlightLayers.length; i++) {
  26625. var highlightLayer = highlightLayers[i];
  26626. if (highlightLayer) {
  26627. highlightLayer.removeMesh(this);
  26628. highlightLayer.removeExcludedMesh(this);
  26629. }
  26630. }
  26631. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26632. };
  26633. /**
  26634. * Modifies the mesh geometry according to a displacement map.
  26635. * 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.
  26636. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26637. * This method returns nothing.
  26638. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26639. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26640. * 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.
  26641. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26642. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26643. *
  26644. * Returns the Mesh.
  26645. */
  26646. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26647. var _this = this;
  26648. var scene = this.getScene();
  26649. var onload = function (img) {
  26650. // Getting height map data
  26651. var canvas = document.createElement("canvas");
  26652. var context = canvas.getContext("2d");
  26653. var heightMapWidth = img.width;
  26654. var heightMapHeight = img.height;
  26655. canvas.width = heightMapWidth;
  26656. canvas.height = heightMapHeight;
  26657. context.drawImage(img, 0, 0);
  26658. // Create VertexData from map data
  26659. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26660. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26661. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26662. //execute success callback, if set
  26663. if (onSuccess) {
  26664. onSuccess(_this);
  26665. }
  26666. };
  26667. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26668. return this;
  26669. };
  26670. /**
  26671. * Modifies the mesh geometry according to a displacementMap buffer.
  26672. * 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.
  26673. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26674. * This method returns nothing.
  26675. * 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.
  26676. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26677. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26678. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26679. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26680. *
  26681. * Returns the Mesh.
  26682. */
  26683. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26684. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26685. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26686. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26687. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26688. return this;
  26689. }
  26690. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26691. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26692. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26693. var position = BABYLON.Vector3.Zero();
  26694. var normal = BABYLON.Vector3.Zero();
  26695. var uv = BABYLON.Vector2.Zero();
  26696. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26697. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26698. for (var index = 0; index < positions.length; index += 3) {
  26699. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26700. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26701. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26702. // Compute height
  26703. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26704. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26705. var pos = (u + v * heightMapWidth) * 4;
  26706. var r = buffer[pos] / 255.0;
  26707. var g = buffer[pos + 1] / 255.0;
  26708. var b = buffer[pos + 2] / 255.0;
  26709. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26710. normal.normalize();
  26711. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26712. position = position.add(normal);
  26713. position.toArray(positions, index);
  26714. }
  26715. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26716. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26717. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26718. return this;
  26719. };
  26720. /**
  26721. * Modify the mesh to get a flat shading rendering.
  26722. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26723. * This method returns the Mesh.
  26724. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26725. */
  26726. Mesh.prototype.convertToFlatShadedMesh = function () {
  26727. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26728. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26729. var kinds = this.getVerticesDataKinds();
  26730. var vbs = {};
  26731. var data = {};
  26732. var newdata = {};
  26733. var updatableNormals = false;
  26734. var kindIndex;
  26735. var kind;
  26736. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26737. kind = kinds[kindIndex];
  26738. var vertexBuffer = this.getVertexBuffer(kind);
  26739. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26740. updatableNormals = vertexBuffer.isUpdatable();
  26741. kinds.splice(kindIndex, 1);
  26742. kindIndex--;
  26743. continue;
  26744. }
  26745. vbs[kind] = vertexBuffer;
  26746. data[kind] = vbs[kind].getData();
  26747. newdata[kind] = [];
  26748. }
  26749. // Save previous submeshes
  26750. var previousSubmeshes = this.subMeshes.slice(0);
  26751. var indices = this.getIndices();
  26752. var totalIndices = this.getTotalIndices();
  26753. // Generating unique vertices per face
  26754. var index;
  26755. for (index = 0; index < totalIndices; index++) {
  26756. var vertexIndex = indices[index];
  26757. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26758. kind = kinds[kindIndex];
  26759. var stride = vbs[kind].getStrideSize();
  26760. for (var offset = 0; offset < stride; offset++) {
  26761. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26762. }
  26763. }
  26764. }
  26765. // Updating faces & normal
  26766. var normals = [];
  26767. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26768. for (index = 0; index < totalIndices; index += 3) {
  26769. indices[index] = index;
  26770. indices[index + 1] = index + 1;
  26771. indices[index + 2] = index + 2;
  26772. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26773. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26774. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26775. var p1p2 = p1.subtract(p2);
  26776. var p3p2 = p3.subtract(p2);
  26777. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26778. // Store same normals for every vertex
  26779. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26780. normals.push(normal.x);
  26781. normals.push(normal.y);
  26782. normals.push(normal.z);
  26783. }
  26784. }
  26785. this.setIndices(indices);
  26786. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26787. // Updating vertex buffers
  26788. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26789. kind = kinds[kindIndex];
  26790. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26791. }
  26792. // Updating submeshes
  26793. this.releaseSubMeshes();
  26794. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26795. var previousOne = previousSubmeshes[submeshIndex];
  26796. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26797. }
  26798. this.synchronizeInstances();
  26799. return this;
  26800. };
  26801. /**
  26802. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26803. * In other words, more vertices, no more indices and a single bigger VBO.
  26804. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26805. * Returns the Mesh.
  26806. */
  26807. Mesh.prototype.convertToUnIndexedMesh = function () {
  26808. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26809. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26810. var kinds = this.getVerticesDataKinds();
  26811. var vbs = {};
  26812. var data = {};
  26813. var newdata = {};
  26814. var kindIndex;
  26815. var kind;
  26816. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26817. kind = kinds[kindIndex];
  26818. var vertexBuffer = this.getVertexBuffer(kind);
  26819. vbs[kind] = vertexBuffer;
  26820. data[kind] = vbs[kind].getData();
  26821. newdata[kind] = [];
  26822. }
  26823. // Save previous submeshes
  26824. var previousSubmeshes = this.subMeshes.slice(0);
  26825. var indices = this.getIndices();
  26826. var totalIndices = this.getTotalIndices();
  26827. // Generating unique vertices per face
  26828. var index;
  26829. for (index = 0; index < totalIndices; index++) {
  26830. var vertexIndex = indices[index];
  26831. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26832. kind = kinds[kindIndex];
  26833. var stride = vbs[kind].getStrideSize();
  26834. for (var offset = 0; offset < stride; offset++) {
  26835. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26836. }
  26837. }
  26838. }
  26839. // Updating indices
  26840. for (index = 0; index < totalIndices; index += 3) {
  26841. indices[index] = index;
  26842. indices[index + 1] = index + 1;
  26843. indices[index + 2] = index + 2;
  26844. }
  26845. this.setIndices(indices);
  26846. // Updating vertex buffers
  26847. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26848. kind = kinds[kindIndex];
  26849. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26850. }
  26851. // Updating submeshes
  26852. this.releaseSubMeshes();
  26853. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26854. var previousOne = previousSubmeshes[submeshIndex];
  26855. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26856. }
  26857. this._unIndexed = true;
  26858. this.synchronizeInstances();
  26859. return this;
  26860. };
  26861. /**
  26862. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26863. * This method returns the Mesh.
  26864. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26865. */
  26866. Mesh.prototype.flipFaces = function (flipNormals) {
  26867. if (flipNormals === void 0) { flipNormals = false; }
  26868. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26869. var i;
  26870. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26871. for (i = 0; i < vertex_data.normals.length; i++) {
  26872. vertex_data.normals[i] *= -1;
  26873. }
  26874. }
  26875. if (vertex_data.indices) {
  26876. var temp;
  26877. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26878. // reassign indices
  26879. temp = vertex_data.indices[i + 1];
  26880. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26881. vertex_data.indices[i + 2] = temp;
  26882. }
  26883. }
  26884. vertex_data.applyToMesh(this);
  26885. return this;
  26886. };
  26887. // Instances
  26888. /**
  26889. * Creates a new InstancedMesh object from the mesh model.
  26890. * An instance shares the same properties and the same material than its model.
  26891. * Only these properties of each instance can then be set individually :
  26892. * - position
  26893. * - rotation
  26894. * - rotationQuaternion
  26895. * - setPivotMatrix
  26896. * - scaling
  26897. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26898. * Warning : this method is not supported for Line mesh and LineSystem
  26899. */
  26900. Mesh.prototype.createInstance = function (name) {
  26901. return new BABYLON.InstancedMesh(name, this);
  26902. };
  26903. /**
  26904. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26905. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26906. * This method returns the Mesh.
  26907. */
  26908. Mesh.prototype.synchronizeInstances = function () {
  26909. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26910. var instance = this.instances[instanceIndex];
  26911. instance._syncSubMeshes();
  26912. }
  26913. return this;
  26914. };
  26915. /**
  26916. * Simplify the mesh according to the given array of settings.
  26917. * Function will return immediately and will simplify async. It returns the Mesh.
  26918. * @param settings a collection of simplification settings.
  26919. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26920. * @param type the type of simplification to run.
  26921. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26922. */
  26923. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26924. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26925. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26926. this.getScene().simplificationQueue.addTask({
  26927. settings: settings,
  26928. parallelProcessing: parallelProcessing,
  26929. mesh: this,
  26930. simplificationType: simplificationType,
  26931. successCallback: successCallback
  26932. });
  26933. return this;
  26934. };
  26935. /**
  26936. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26937. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26938. * This should be used together with the simplification to avoid disappearing triangles.
  26939. * Returns the Mesh.
  26940. * @param successCallback an optional success callback to be called after the optimization finished.
  26941. */
  26942. Mesh.prototype.optimizeIndices = function (successCallback) {
  26943. var _this = this;
  26944. var indices = this.getIndices();
  26945. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26946. if (!positions || !indices) {
  26947. return this;
  26948. }
  26949. var vectorPositions = new Array();
  26950. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26951. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26952. }
  26953. var dupes = new Array();
  26954. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26955. var realPos = vectorPositions.length - 1 - iteration;
  26956. var testedPosition = vectorPositions[realPos];
  26957. for (var j = 0; j < realPos; ++j) {
  26958. var againstPosition = vectorPositions[j];
  26959. if (testedPosition.equals(againstPosition)) {
  26960. dupes[realPos] = j;
  26961. break;
  26962. }
  26963. }
  26964. }, function () {
  26965. for (var i = 0; i < indices.length; ++i) {
  26966. indices[i] = dupes[indices[i]] || indices[i];
  26967. }
  26968. //indices are now reordered
  26969. var originalSubMeshes = _this.subMeshes.slice(0);
  26970. _this.setIndices(indices);
  26971. _this.subMeshes = originalSubMeshes;
  26972. if (successCallback) {
  26973. successCallback(_this);
  26974. }
  26975. });
  26976. return this;
  26977. };
  26978. Mesh.prototype.serialize = function (serializationObject) {
  26979. serializationObject.name = this.name;
  26980. serializationObject.id = this.id;
  26981. serializationObject.type = this.getClassName();
  26982. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26983. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26984. }
  26985. serializationObject.position = this.position.asArray();
  26986. if (this.rotationQuaternion) {
  26987. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26988. }
  26989. else if (this.rotation) {
  26990. serializationObject.rotation = this.rotation.asArray();
  26991. }
  26992. serializationObject.scaling = this.scaling.asArray();
  26993. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26994. serializationObject.isEnabled = this.isEnabled(false);
  26995. serializationObject.isVisible = this.isVisible;
  26996. serializationObject.infiniteDistance = this.infiniteDistance;
  26997. serializationObject.pickable = this.isPickable;
  26998. serializationObject.receiveShadows = this.receiveShadows;
  26999. serializationObject.billboardMode = this.billboardMode;
  27000. serializationObject.visibility = this.visibility;
  27001. serializationObject.checkCollisions = this.checkCollisions;
  27002. serializationObject.isBlocker = this.isBlocker;
  27003. // Parent
  27004. if (this.parent) {
  27005. serializationObject.parentId = this.parent.id;
  27006. }
  27007. // Geometry
  27008. serializationObject.isUnIndexed = this.isUnIndexed;
  27009. var geometry = this._geometry;
  27010. if (geometry) {
  27011. var geometryId = geometry.id;
  27012. serializationObject.geometryId = geometryId;
  27013. // SubMeshes
  27014. serializationObject.subMeshes = [];
  27015. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27016. var subMesh = this.subMeshes[subIndex];
  27017. serializationObject.subMeshes.push({
  27018. materialIndex: subMesh.materialIndex,
  27019. verticesStart: subMesh.verticesStart,
  27020. verticesCount: subMesh.verticesCount,
  27021. indexStart: subMesh.indexStart,
  27022. indexCount: subMesh.indexCount
  27023. });
  27024. }
  27025. }
  27026. // Material
  27027. if (this.material) {
  27028. serializationObject.materialId = this.material.id;
  27029. }
  27030. else {
  27031. this.material = null;
  27032. }
  27033. // Morph targets
  27034. if (this.morphTargetManager) {
  27035. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27036. }
  27037. // Skeleton
  27038. if (this.skeleton) {
  27039. serializationObject.skeletonId = this.skeleton.id;
  27040. }
  27041. // Physics
  27042. //TODO implement correct serialization for physics impostors.
  27043. var impostor = this.getPhysicsImpostor();
  27044. if (impostor) {
  27045. serializationObject.physicsMass = impostor.getParam("mass");
  27046. serializationObject.physicsFriction = impostor.getParam("friction");
  27047. serializationObject.physicsRestitution = impostor.getParam("mass");
  27048. serializationObject.physicsImpostor = impostor.type;
  27049. }
  27050. // Metadata
  27051. if (this.metadata) {
  27052. serializationObject.metadata = this.metadata;
  27053. }
  27054. // Instances
  27055. serializationObject.instances = [];
  27056. for (var index = 0; index < this.instances.length; index++) {
  27057. var instance = this.instances[index];
  27058. var serializationInstance = {
  27059. name: instance.name,
  27060. id: instance.id,
  27061. position: instance.position.asArray(),
  27062. scaling: instance.scaling.asArray()
  27063. };
  27064. if (instance.rotationQuaternion) {
  27065. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27066. }
  27067. else if (instance.rotation) {
  27068. serializationInstance.rotation = instance.rotation.asArray();
  27069. }
  27070. serializationObject.instances.push(serializationInstance);
  27071. // Animations
  27072. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27073. serializationInstance.ranges = instance.serializeAnimationRanges();
  27074. }
  27075. //
  27076. // Animations
  27077. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27078. serializationObject.ranges = this.serializeAnimationRanges();
  27079. // Layer mask
  27080. serializationObject.layerMask = this.layerMask;
  27081. // Alpha
  27082. serializationObject.alphaIndex = this.alphaIndex;
  27083. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27084. // Overlay
  27085. serializationObject.overlayAlpha = this.overlayAlpha;
  27086. serializationObject.overlayColor = this.overlayColor.asArray();
  27087. serializationObject.renderOverlay = this.renderOverlay;
  27088. // Fog
  27089. serializationObject.applyFog = this.applyFog;
  27090. // Action Manager
  27091. if (this.actionManager) {
  27092. serializationObject.actions = this.actionManager.serialize(this.name);
  27093. }
  27094. };
  27095. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27096. if (!this.geometry) {
  27097. return;
  27098. }
  27099. this._markSubMeshesAsAttributesDirty();
  27100. var morphTargetManager = this._morphTargetManager;
  27101. if (morphTargetManager && morphTargetManager.vertexCount) {
  27102. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27103. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27104. this.morphTargetManager = null;
  27105. return;
  27106. }
  27107. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27108. var morphTarget = morphTargetManager.getActiveTarget(index);
  27109. var positions = morphTarget.getPositions();
  27110. if (!positions) {
  27111. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27112. return;
  27113. }
  27114. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27115. var normals = morphTarget.getNormals();
  27116. if (normals) {
  27117. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27118. }
  27119. var tangents = morphTarget.getTangents();
  27120. if (tangents) {
  27121. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27122. }
  27123. }
  27124. }
  27125. else {
  27126. var index = 0;
  27127. // Positions
  27128. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27129. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27130. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27131. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27132. }
  27133. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27134. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27135. }
  27136. index++;
  27137. }
  27138. }
  27139. };
  27140. // Statics
  27141. /**
  27142. * Returns a new Mesh object parsed from the source provided.
  27143. * The parameter `parsedMesh` is the source.
  27144. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27145. */
  27146. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27147. var mesh;
  27148. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27149. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27150. }
  27151. else {
  27152. mesh = new Mesh(parsedMesh.name, scene);
  27153. }
  27154. mesh.id = parsedMesh.id;
  27155. if (BABYLON.Tags) {
  27156. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27157. }
  27158. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27159. if (parsedMesh.metadata !== undefined) {
  27160. mesh.metadata = parsedMesh.metadata;
  27161. }
  27162. if (parsedMesh.rotationQuaternion) {
  27163. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27164. }
  27165. else if (parsedMesh.rotation) {
  27166. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27167. }
  27168. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27169. if (parsedMesh.localMatrix) {
  27170. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27171. }
  27172. else if (parsedMesh.pivotMatrix) {
  27173. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27174. }
  27175. mesh.setEnabled(parsedMesh.isEnabled);
  27176. mesh.isVisible = parsedMesh.isVisible;
  27177. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27178. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27179. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27180. if (parsedMesh.applyFog !== undefined) {
  27181. mesh.applyFog = parsedMesh.applyFog;
  27182. }
  27183. if (parsedMesh.pickable !== undefined) {
  27184. mesh.isPickable = parsedMesh.pickable;
  27185. }
  27186. if (parsedMesh.alphaIndex !== undefined) {
  27187. mesh.alphaIndex = parsedMesh.alphaIndex;
  27188. }
  27189. mesh.receiveShadows = parsedMesh.receiveShadows;
  27190. mesh.billboardMode = parsedMesh.billboardMode;
  27191. if (parsedMesh.visibility !== undefined) {
  27192. mesh.visibility = parsedMesh.visibility;
  27193. }
  27194. mesh.checkCollisions = parsedMesh.checkCollisions;
  27195. if (parsedMesh.isBlocker !== undefined) {
  27196. mesh.isBlocker = parsedMesh.isBlocker;
  27197. }
  27198. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27199. // freezeWorldMatrix
  27200. if (parsedMesh.freezeWorldMatrix) {
  27201. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27202. }
  27203. // Parent
  27204. if (parsedMesh.parentId) {
  27205. mesh._waitingParentId = parsedMesh.parentId;
  27206. }
  27207. // Actions
  27208. if (parsedMesh.actions !== undefined) {
  27209. mesh._waitingActions = parsedMesh.actions;
  27210. }
  27211. // Overlay
  27212. if (parsedMesh.overlayAlpha !== undefined) {
  27213. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27214. }
  27215. if (parsedMesh.overlayColor !== undefined) {
  27216. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27217. }
  27218. if (parsedMesh.renderOverlay !== undefined) {
  27219. mesh.renderOverlay = parsedMesh.renderOverlay;
  27220. }
  27221. // Geometry
  27222. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27223. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27224. if (parsedMesh.delayLoadingFile) {
  27225. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27226. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27227. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27228. if (parsedMesh._binaryInfo) {
  27229. mesh._binaryInfo = parsedMesh._binaryInfo;
  27230. }
  27231. mesh._delayInfo = [];
  27232. if (parsedMesh.hasUVs) {
  27233. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27234. }
  27235. if (parsedMesh.hasUVs2) {
  27236. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27237. }
  27238. if (parsedMesh.hasUVs3) {
  27239. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27240. }
  27241. if (parsedMesh.hasUVs4) {
  27242. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27243. }
  27244. if (parsedMesh.hasUVs5) {
  27245. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27246. }
  27247. if (parsedMesh.hasUVs6) {
  27248. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27249. }
  27250. if (parsedMesh.hasColors) {
  27251. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27252. }
  27253. if (parsedMesh.hasMatricesIndices) {
  27254. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27255. }
  27256. if (parsedMesh.hasMatricesWeights) {
  27257. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27258. }
  27259. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27260. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27261. mesh._checkDelayState();
  27262. }
  27263. }
  27264. else {
  27265. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27266. }
  27267. // Material
  27268. if (parsedMesh.materialId) {
  27269. mesh.setMaterialByID(parsedMesh.materialId);
  27270. }
  27271. else {
  27272. mesh.material = null;
  27273. }
  27274. // Morph targets
  27275. if (parsedMesh.morphTargetManagerId > -1) {
  27276. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27277. }
  27278. // Skeleton
  27279. if (parsedMesh.skeletonId > -1) {
  27280. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27281. if (parsedMesh.numBoneInfluencers) {
  27282. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27283. }
  27284. }
  27285. // Animations
  27286. if (parsedMesh.animations) {
  27287. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27288. var parsedAnimation = parsedMesh.animations[animationIndex];
  27289. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27290. }
  27291. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27292. }
  27293. if (parsedMesh.autoAnimate) {
  27294. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27295. }
  27296. // Layer Mask
  27297. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27298. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27299. }
  27300. else {
  27301. mesh.layerMask = 0x0FFFFFFF;
  27302. }
  27303. // Physics
  27304. if (parsedMesh.physicsImpostor) {
  27305. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27306. mass: parsedMesh.physicsMass,
  27307. friction: parsedMesh.physicsFriction,
  27308. restitution: parsedMesh.physicsRestitution
  27309. }, scene);
  27310. }
  27311. // Instances
  27312. if (parsedMesh.instances) {
  27313. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27314. var parsedInstance = parsedMesh.instances[index];
  27315. var instance = mesh.createInstance(parsedInstance.name);
  27316. if (parsedInstance.id) {
  27317. instance.id = parsedInstance.id;
  27318. }
  27319. if (BABYLON.Tags) {
  27320. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27321. }
  27322. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27323. if (parsedInstance.parentId) {
  27324. instance._waitingParentId = parsedInstance.parentId;
  27325. }
  27326. if (parsedInstance.rotationQuaternion) {
  27327. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27328. }
  27329. else if (parsedInstance.rotation) {
  27330. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27331. }
  27332. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27333. instance.checkCollisions = mesh.checkCollisions;
  27334. if (parsedMesh.animations) {
  27335. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27336. parsedAnimation = parsedMesh.animations[animationIndex];
  27337. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27338. }
  27339. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27340. }
  27341. }
  27342. }
  27343. return mesh;
  27344. };
  27345. /**
  27346. * Creates a ribbon mesh.
  27347. * Please consider using the same method from the MeshBuilder class instead.
  27348. * 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.
  27349. *
  27350. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27351. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27352. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27353. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27354. * 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.
  27355. * 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.
  27356. * 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
  27357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27358. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27360. */
  27361. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27362. if (closeArray === void 0) { closeArray = false; }
  27363. if (updatable === void 0) { updatable = false; }
  27364. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27365. pathArray: pathArray,
  27366. closeArray: closeArray,
  27367. closePath: closePath,
  27368. offset: offset,
  27369. updatable: updatable,
  27370. sideOrientation: sideOrientation,
  27371. instance: instance
  27372. }, scene);
  27373. };
  27374. /**
  27375. * Creates a plane polygonal mesh. By default, this is a disc.
  27376. * Please consider using the same method from the MeshBuilder class instead.
  27377. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27378. * 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.
  27379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27380. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27382. */
  27383. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27384. if (scene === void 0) { scene = null; }
  27385. var options = {
  27386. radius: radius,
  27387. tessellation: tessellation,
  27388. sideOrientation: sideOrientation,
  27389. updatable: updatable
  27390. };
  27391. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27392. };
  27393. /**
  27394. * Creates a box mesh.
  27395. * Please consider using the same method from the MeshBuilder class instead.
  27396. * The parameter `size` sets the size (float) of each box side (default 1).
  27397. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27398. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27399. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27400. */
  27401. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27402. if (scene === void 0) { scene = null; }
  27403. var options = {
  27404. size: size,
  27405. sideOrientation: sideOrientation,
  27406. updatable: updatable
  27407. };
  27408. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27409. };
  27410. /**
  27411. * Creates a sphere mesh.
  27412. * Please consider using the same method from the MeshBuilder class instead.
  27413. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27414. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27415. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27416. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27418. */
  27419. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27420. var options = {
  27421. segments: segments,
  27422. diameterX: diameter,
  27423. diameterY: diameter,
  27424. diameterZ: diameter,
  27425. sideOrientation: sideOrientation,
  27426. updatable: updatable
  27427. };
  27428. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27429. };
  27430. /**
  27431. * Creates a cylinder or a cone mesh.
  27432. * Please consider using the same method from the MeshBuilder class instead.
  27433. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27434. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27435. * 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.
  27436. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27437. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27438. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27439. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27441. */
  27442. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27443. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27444. if (scene !== undefined) {
  27445. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27446. updatable = scene;
  27447. }
  27448. scene = subdivisions;
  27449. subdivisions = 1;
  27450. }
  27451. var options = {
  27452. height: height,
  27453. diameterTop: diameterTop,
  27454. diameterBottom: diameterBottom,
  27455. tessellation: tessellation,
  27456. subdivisions: subdivisions,
  27457. sideOrientation: sideOrientation,
  27458. updatable: updatable
  27459. };
  27460. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27461. };
  27462. // Torus (Code from SharpDX.org)
  27463. /**
  27464. * Creates a torus mesh.
  27465. * Please consider using the same method from the MeshBuilder class instead.
  27466. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27467. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27468. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27469. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27470. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27472. */
  27473. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27474. var options = {
  27475. diameter: diameter,
  27476. thickness: thickness,
  27477. tessellation: tessellation,
  27478. sideOrientation: sideOrientation,
  27479. updatable: updatable
  27480. };
  27481. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27482. };
  27483. /**
  27484. * Creates a torus knot mesh.
  27485. * Please consider using the same method from the MeshBuilder class instead.
  27486. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27487. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27488. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27489. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27493. */
  27494. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27495. var options = {
  27496. radius: radius,
  27497. tube: tube,
  27498. radialSegments: radialSegments,
  27499. tubularSegments: tubularSegments,
  27500. p: p,
  27501. q: q,
  27502. sideOrientation: sideOrientation,
  27503. updatable: updatable
  27504. };
  27505. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27506. };
  27507. /**
  27508. * Creates a line mesh.
  27509. * Please consider using the same method from the MeshBuilder class instead.
  27510. * 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.
  27511. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27512. * The parameter `points` is an array successive Vector3.
  27513. * 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
  27514. * When updating an instance, remember that only point positions can change, not the number of points.
  27515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27516. */
  27517. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27518. if (scene === void 0) { scene = null; }
  27519. if (updatable === void 0) { updatable = false; }
  27520. if (instance === void 0) { instance = null; }
  27521. var options = {
  27522. points: points,
  27523. updatable: updatable,
  27524. instance: instance
  27525. };
  27526. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27527. };
  27528. /**
  27529. * Creates a dashed line mesh.
  27530. * Please consider using the same method from the MeshBuilder class instead.
  27531. * 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.
  27532. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27533. * The parameter `points` is an array successive Vector3.
  27534. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27535. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27536. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27537. * 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
  27538. * When updating an instance, remember that only point positions can change, not the number of points.
  27539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27540. */
  27541. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27542. if (scene === void 0) { scene = null; }
  27543. var options = {
  27544. points: points,
  27545. dashSize: dashSize,
  27546. gapSize: gapSize,
  27547. dashNb: dashNb,
  27548. updatable: updatable,
  27549. instance: instance
  27550. };
  27551. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27552. };
  27553. /**
  27554. * Creates a polygon mesh.
  27555. * Please consider using the same method from the MeshBuilder class instead.
  27556. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27557. * 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.
  27558. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27560. * Remember you can only change the shape positions, not their number when updating a polygon.
  27561. */
  27562. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27563. var options = {
  27564. shape: shape,
  27565. holes: holes,
  27566. updatable: updatable,
  27567. sideOrientation: sideOrientation
  27568. };
  27569. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27570. };
  27571. /**
  27572. * Creates an extruded polygon mesh, with depth in the Y direction.
  27573. * Please consider using the same method from the MeshBuilder class instead.
  27574. */
  27575. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27576. var options = {
  27577. shape: shape,
  27578. holes: holes,
  27579. depth: depth,
  27580. updatable: updatable,
  27581. sideOrientation: sideOrientation
  27582. };
  27583. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27584. };
  27585. /**
  27586. * Creates an extruded shape mesh.
  27587. * 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.
  27588. * Please consider using the same method from the MeshBuilder class instead.
  27589. *
  27590. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27591. * 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
  27592. * extruded along the Z axis.
  27593. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27594. * 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.
  27595. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27596. * 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
  27597. * 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
  27598. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27599. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27600. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27602. */
  27603. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27604. if (scene === void 0) { scene = null; }
  27605. var options = {
  27606. shape: shape,
  27607. path: path,
  27608. scale: scale,
  27609. rotation: rotation,
  27610. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27611. sideOrientation: sideOrientation,
  27612. instance: instance,
  27613. updatable: updatable
  27614. };
  27615. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27616. };
  27617. /**
  27618. * Creates an custom extruded shape mesh.
  27619. * 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.
  27620. * Please consider using the same method from the MeshBuilder class instead.
  27621. *
  27622. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27623. * 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
  27624. * extruded along the Z axis.
  27625. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27626. * 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
  27627. * and the distance of this point from the begining of the path :
  27628. * ```javascript
  27629. * var rotationFunction = function(i, distance) {
  27630. * // do things
  27631. * return rotationValue; }
  27632. * ```
  27633. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27634. * 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
  27635. * and the distance of this point from the begining of the path :
  27636. * ```javascript
  27637. * var scaleFunction = function(i, distance) {
  27638. * // do things
  27639. * return scaleValue;}
  27640. * ```
  27641. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27642. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27643. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27644. * 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
  27645. * 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
  27646. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27647. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27648. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27649. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27650. */
  27651. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27652. var options = {
  27653. shape: shape,
  27654. path: path,
  27655. scaleFunction: scaleFunction,
  27656. rotationFunction: rotationFunction,
  27657. ribbonCloseArray: ribbonCloseArray,
  27658. ribbonClosePath: ribbonClosePath,
  27659. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27660. sideOrientation: sideOrientation,
  27661. instance: instance,
  27662. updatable: updatable
  27663. };
  27664. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27665. };
  27666. /**
  27667. * Creates lathe mesh.
  27668. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27669. * Please consider using the same method from the MeshBuilder class instead.
  27670. * 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
  27671. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27672. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27673. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27674. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27675. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27676. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27677. */
  27678. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27679. var options = {
  27680. shape: shape,
  27681. radius: radius,
  27682. tessellation: tessellation,
  27683. sideOrientation: sideOrientation,
  27684. updatable: updatable
  27685. };
  27686. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27687. };
  27688. /**
  27689. * Creates a plane mesh.
  27690. * Please consider using the same method from the MeshBuilder class instead.
  27691. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27695. */
  27696. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27697. var options = {
  27698. size: size,
  27699. width: size,
  27700. height: size,
  27701. sideOrientation: sideOrientation,
  27702. updatable: updatable
  27703. };
  27704. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27705. };
  27706. /**
  27707. * Creates a ground mesh.
  27708. * Please consider using the same method from the MeshBuilder class instead.
  27709. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27710. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27712. */
  27713. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27714. var options = {
  27715. width: width,
  27716. height: height,
  27717. subdivisions: subdivisions,
  27718. updatable: updatable
  27719. };
  27720. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27721. };
  27722. /**
  27723. * Creates a tiled ground mesh.
  27724. * Please consider using the same method from the MeshBuilder class instead.
  27725. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27726. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27727. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27728. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27729. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27730. * numbers of subdivisions on the ground width and height of each tile.
  27731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27732. */
  27733. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27734. var options = {
  27735. xmin: xmin,
  27736. zmin: zmin,
  27737. xmax: xmax,
  27738. zmax: zmax,
  27739. subdivisions: subdivisions,
  27740. precision: precision,
  27741. updatable: updatable
  27742. };
  27743. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27744. };
  27745. /**
  27746. * Creates a ground mesh from a height map.
  27747. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27748. * Please consider using the same method from the MeshBuilder class instead.
  27749. * The parameter `url` sets the URL of the height map image resource.
  27750. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27751. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27752. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27753. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27754. * 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).
  27755. * This function is passed the newly built mesh :
  27756. * ```javascript
  27757. * function(mesh) { // do things
  27758. * return; }
  27759. * ```
  27760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27761. */
  27762. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27763. var options = {
  27764. width: width,
  27765. height: height,
  27766. subdivisions: subdivisions,
  27767. minHeight: minHeight,
  27768. maxHeight: maxHeight,
  27769. updatable: updatable,
  27770. onReady: onReady
  27771. };
  27772. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27773. };
  27774. /**
  27775. * Creates a tube mesh.
  27776. * 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.
  27777. * Please consider using the same method from the MeshBuilder class instead.
  27778. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27779. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27780. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27781. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27782. * 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.
  27783. * It must return a radius value (positive float) :
  27784. * ```javascript
  27785. * var radiusFunction = function(i, distance) {
  27786. * // do things
  27787. * return radius; }
  27788. * ```
  27789. * 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
  27790. * 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
  27791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27794. */
  27795. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27796. var options = {
  27797. path: path,
  27798. radius: radius,
  27799. tessellation: tessellation,
  27800. radiusFunction: radiusFunction,
  27801. arc: 1,
  27802. cap: cap,
  27803. updatable: updatable,
  27804. sideOrientation: sideOrientation,
  27805. instance: instance
  27806. };
  27807. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27808. };
  27809. /**
  27810. * Creates a polyhedron mesh.
  27811. * Please consider using the same method from the MeshBuilder class instead.
  27812. * 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
  27813. * to choose the wanted type.
  27814. * The parameter `size` (positive float, default 1) sets the polygon size.
  27815. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27816. * 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`.
  27817. * 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
  27818. * 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)`).
  27819. * 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
  27820. * 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.
  27821. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27822. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27824. */
  27825. Mesh.CreatePolyhedron = function (name, options, scene) {
  27826. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27827. };
  27828. /**
  27829. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27830. * Please consider using the same method from the MeshBuilder class instead.
  27831. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27832. * 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`).
  27833. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27834. * 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.
  27835. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27836. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27837. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27838. */
  27839. Mesh.CreateIcoSphere = function (name, options, scene) {
  27840. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27841. };
  27842. /**
  27843. * Creates a decal mesh.
  27844. * Please consider using the same method from the MeshBuilder class instead.
  27845. * 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.
  27846. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27847. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27848. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27849. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27850. */
  27851. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27852. var options = {
  27853. position: position,
  27854. normal: normal,
  27855. size: size,
  27856. angle: angle
  27857. };
  27858. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27859. };
  27860. // Skeletons
  27861. /**
  27862. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27863. */
  27864. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27865. if (!this._sourcePositions) {
  27866. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27867. if (!source) {
  27868. return this._sourcePositions;
  27869. }
  27870. this._sourcePositions = new Float32Array(source);
  27871. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27872. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27873. }
  27874. }
  27875. return this._sourcePositions;
  27876. };
  27877. /**
  27878. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27879. */
  27880. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27881. if (!this._sourceNormals) {
  27882. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27883. if (!source) {
  27884. return this._sourceNormals;
  27885. }
  27886. this._sourceNormals = new Float32Array(source);
  27887. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27888. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27889. }
  27890. }
  27891. return this._sourceNormals;
  27892. };
  27893. /**
  27894. * Updates the vertex buffer by applying transformation from the bones.
  27895. * Returns the Mesh.
  27896. *
  27897. * @param {skeleton} skeleton to apply
  27898. */
  27899. Mesh.prototype.applySkeleton = function (skeleton) {
  27900. if (!this.geometry) {
  27901. return this;
  27902. }
  27903. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27904. return this;
  27905. }
  27906. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27907. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27908. return this;
  27909. }
  27910. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27911. return this;
  27912. }
  27913. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27914. return this;
  27915. }
  27916. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27917. return this;
  27918. }
  27919. if (!this._sourcePositions) {
  27920. var submeshes = this.subMeshes.slice();
  27921. this.setPositionsForCPUSkinning();
  27922. this.subMeshes = submeshes;
  27923. }
  27924. if (!this._sourceNormals) {
  27925. this.setNormalsForCPUSkinning();
  27926. }
  27927. // positionsData checks for not being Float32Array will only pass at most once
  27928. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27929. if (!positionsData) {
  27930. return this;
  27931. }
  27932. if (!(positionsData instanceof Float32Array)) {
  27933. positionsData = new Float32Array(positionsData);
  27934. }
  27935. // normalsData checks for not being Float32Array will only pass at most once
  27936. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27937. if (!normalsData) {
  27938. return this;
  27939. }
  27940. if (!(normalsData instanceof Float32Array)) {
  27941. normalsData = new Float32Array(normalsData);
  27942. }
  27943. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27944. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27945. if (!matricesWeightsData || !matricesIndicesData) {
  27946. return this;
  27947. }
  27948. var needExtras = this.numBoneInfluencers > 4;
  27949. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27950. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27951. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27952. var tempVector3 = BABYLON.Vector3.Zero();
  27953. var finalMatrix = new BABYLON.Matrix();
  27954. var tempMatrix = new BABYLON.Matrix();
  27955. var matWeightIdx = 0;
  27956. var inf;
  27957. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27958. var weight;
  27959. for (inf = 0; inf < 4; inf++) {
  27960. weight = matricesWeightsData[matWeightIdx + inf];
  27961. if (weight > 0) {
  27962. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27963. finalMatrix.addToSelf(tempMatrix);
  27964. }
  27965. else
  27966. break;
  27967. }
  27968. if (needExtras) {
  27969. for (inf = 0; inf < 4; inf++) {
  27970. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27971. if (weight > 0) {
  27972. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27973. finalMatrix.addToSelf(tempMatrix);
  27974. }
  27975. else
  27976. break;
  27977. }
  27978. }
  27979. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27980. tempVector3.toArray(positionsData, index);
  27981. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27982. tempVector3.toArray(normalsData, index);
  27983. finalMatrix.reset();
  27984. }
  27985. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27986. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27987. return this;
  27988. };
  27989. // Tools
  27990. /**
  27991. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27992. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27993. */
  27994. Mesh.MinMax = function (meshes) {
  27995. var minVector = null;
  27996. var maxVector = null;
  27997. meshes.forEach(function (mesh, index, array) {
  27998. var boundingInfo = mesh.getBoundingInfo();
  27999. var boundingBox = boundingInfo.boundingBox;
  28000. if (!minVector || !maxVector) {
  28001. minVector = boundingBox.minimumWorld;
  28002. maxVector = boundingBox.maximumWorld;
  28003. }
  28004. else {
  28005. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28006. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28007. }
  28008. });
  28009. if (!minVector || !maxVector) {
  28010. return {
  28011. min: BABYLON.Vector3.Zero(),
  28012. max: BABYLON.Vector3.Zero()
  28013. };
  28014. }
  28015. return {
  28016. min: minVector,
  28017. max: maxVector
  28018. };
  28019. };
  28020. /**
  28021. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28022. */
  28023. Mesh.Center = function (meshesOrMinMaxVector) {
  28024. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28025. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28026. };
  28027. /**
  28028. * Merge the array of meshes into a single mesh for performance reasons.
  28029. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28030. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28031. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28032. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28033. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28034. */
  28035. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28036. if (disposeSource === void 0) { disposeSource = true; }
  28037. var index;
  28038. if (!allow32BitsIndices) {
  28039. var totalVertices = 0;
  28040. // Counting vertices
  28041. for (index = 0; index < meshes.length; index++) {
  28042. if (meshes[index]) {
  28043. totalVertices += meshes[index].getTotalVertices();
  28044. if (totalVertices > 65536) {
  28045. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28046. return null;
  28047. }
  28048. }
  28049. }
  28050. }
  28051. // Merge
  28052. var vertexData = null;
  28053. var otherVertexData;
  28054. var indiceArray = new Array();
  28055. var source = null;
  28056. for (index = 0; index < meshes.length; index++) {
  28057. if (meshes[index]) {
  28058. meshes[index].computeWorldMatrix(true);
  28059. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28060. otherVertexData.transform(meshes[index].getWorldMatrix());
  28061. if (vertexData) {
  28062. vertexData.merge(otherVertexData);
  28063. }
  28064. else {
  28065. vertexData = otherVertexData;
  28066. source = meshes[index];
  28067. }
  28068. if (subdivideWithSubMeshes) {
  28069. indiceArray.push(meshes[index].getTotalIndices());
  28070. }
  28071. }
  28072. }
  28073. source = source;
  28074. if (!meshSubclass) {
  28075. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28076. }
  28077. vertexData.applyToMesh(meshSubclass);
  28078. // Setting properties
  28079. meshSubclass.material = source.material;
  28080. meshSubclass.checkCollisions = source.checkCollisions;
  28081. // Cleaning
  28082. if (disposeSource) {
  28083. for (index = 0; index < meshes.length; index++) {
  28084. if (meshes[index]) {
  28085. meshes[index].dispose();
  28086. }
  28087. }
  28088. }
  28089. // Subdivide
  28090. if (subdivideWithSubMeshes) {
  28091. //-- Suppresions du submesh global
  28092. meshSubclass.releaseSubMeshes();
  28093. index = 0;
  28094. var offset = 0;
  28095. //-- aplique la subdivision en fonction du tableau d'indices
  28096. while (index < indiceArray.length) {
  28097. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28098. offset += indiceArray[index];
  28099. index++;
  28100. }
  28101. }
  28102. return meshSubclass;
  28103. };
  28104. // Consts
  28105. Mesh._FRONTSIDE = 0;
  28106. Mesh._BACKSIDE = 1;
  28107. Mesh._DOUBLESIDE = 2;
  28108. Mesh._DEFAULTSIDE = 0;
  28109. Mesh._NO_CAP = 0;
  28110. Mesh._CAP_START = 1;
  28111. Mesh._CAP_END = 2;
  28112. Mesh._CAP_ALL = 3;
  28113. return Mesh;
  28114. }(BABYLON.AbstractMesh));
  28115. BABYLON.Mesh = Mesh;
  28116. })(BABYLON || (BABYLON = {}));
  28117. //# sourceMappingURL=babylon.mesh.js.map
  28118. var BABYLON;
  28119. (function (BABYLON) {
  28120. var BaseSubMesh = /** @class */ (function () {
  28121. function BaseSubMesh() {
  28122. }
  28123. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28124. get: function () {
  28125. return this._materialEffect;
  28126. },
  28127. enumerable: true,
  28128. configurable: true
  28129. });
  28130. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28131. if (defines === void 0) { defines = null; }
  28132. if (this._materialEffect === effect) {
  28133. if (!effect) {
  28134. this._materialDefines = null;
  28135. }
  28136. return;
  28137. }
  28138. this._materialDefines = defines;
  28139. this._materialEffect = effect;
  28140. };
  28141. return BaseSubMesh;
  28142. }());
  28143. BABYLON.BaseSubMesh = BaseSubMesh;
  28144. var SubMesh = /** @class */ (function (_super) {
  28145. __extends(SubMesh, _super);
  28146. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28147. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28148. var _this = _super.call(this) || this;
  28149. _this.materialIndex = materialIndex;
  28150. _this.verticesStart = verticesStart;
  28151. _this.verticesCount = verticesCount;
  28152. _this.indexStart = indexStart;
  28153. _this.indexCount = indexCount;
  28154. _this._renderId = 0;
  28155. _this._mesh = mesh;
  28156. _this._renderingMesh = renderingMesh || mesh;
  28157. mesh.subMeshes.push(_this);
  28158. _this._trianglePlanes = [];
  28159. _this._id = mesh.subMeshes.length - 1;
  28160. if (createBoundingBox) {
  28161. _this.refreshBoundingInfo();
  28162. mesh.computeWorldMatrix(true);
  28163. }
  28164. return _this;
  28165. }
  28166. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28167. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28168. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28169. };
  28170. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28171. get: function () {
  28172. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28173. },
  28174. enumerable: true,
  28175. configurable: true
  28176. });
  28177. /**
  28178. * Returns the submesh BoudingInfo object.
  28179. */
  28180. SubMesh.prototype.getBoundingInfo = function () {
  28181. if (this.IsGlobal) {
  28182. return this._mesh.getBoundingInfo();
  28183. }
  28184. return this._boundingInfo;
  28185. };
  28186. /**
  28187. * Sets the submesh BoundingInfo.
  28188. * Return the SubMesh.
  28189. */
  28190. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28191. this._boundingInfo = boundingInfo;
  28192. return this;
  28193. };
  28194. /**
  28195. * Returns the mesh of the current submesh.
  28196. */
  28197. SubMesh.prototype.getMesh = function () {
  28198. return this._mesh;
  28199. };
  28200. /**
  28201. * Returns the rendering mesh of the submesh.
  28202. */
  28203. SubMesh.prototype.getRenderingMesh = function () {
  28204. return this._renderingMesh;
  28205. };
  28206. /**
  28207. * Returns the submesh material.
  28208. */
  28209. SubMesh.prototype.getMaterial = function () {
  28210. var rootMaterial = this._renderingMesh.material;
  28211. if (rootMaterial === null || rootMaterial === undefined) {
  28212. return this._mesh.getScene().defaultMaterial;
  28213. }
  28214. else if (rootMaterial.getSubMaterial) {
  28215. var multiMaterial = rootMaterial;
  28216. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28217. if (this._currentMaterial !== effectiveMaterial) {
  28218. this._currentMaterial = effectiveMaterial;
  28219. this._materialDefines = null;
  28220. }
  28221. return effectiveMaterial;
  28222. }
  28223. return rootMaterial;
  28224. };
  28225. // Methods
  28226. /**
  28227. * Sets a new updated BoundingInfo object to the submesh.
  28228. * Returns the SubMesh.
  28229. */
  28230. SubMesh.prototype.refreshBoundingInfo = function () {
  28231. this._lastColliderWorldVertices = null;
  28232. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28233. return this;
  28234. }
  28235. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28236. if (!data) {
  28237. this._boundingInfo = this._mesh.getBoundingInfo();
  28238. return this;
  28239. }
  28240. var indices = this._renderingMesh.getIndices();
  28241. var extend;
  28242. //is this the only submesh?
  28243. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28244. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28245. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28246. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28247. }
  28248. else {
  28249. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28250. }
  28251. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28252. return this;
  28253. };
  28254. SubMesh.prototype._checkCollision = function (collider) {
  28255. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28256. return boundingInfo._checkCollision(collider);
  28257. };
  28258. /**
  28259. * Updates the submesh BoundingInfo.
  28260. * Returns the Submesh.
  28261. */
  28262. SubMesh.prototype.updateBoundingInfo = function (world) {
  28263. var boundingInfo = this.getBoundingInfo();
  28264. if (!boundingInfo) {
  28265. this.refreshBoundingInfo();
  28266. boundingInfo = this.getBoundingInfo();
  28267. }
  28268. boundingInfo.update(world);
  28269. return this;
  28270. };
  28271. /**
  28272. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28273. * Boolean returned.
  28274. */
  28275. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28276. var boundingInfo = this.getBoundingInfo();
  28277. if (!boundingInfo) {
  28278. return false;
  28279. }
  28280. return boundingInfo.isInFrustum(frustumPlanes);
  28281. };
  28282. /**
  28283. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28284. * Boolean returned.
  28285. */
  28286. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28287. var boundingInfo = this.getBoundingInfo();
  28288. if (!boundingInfo) {
  28289. return false;
  28290. }
  28291. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28292. };
  28293. /**
  28294. * Renders the submesh.
  28295. * Returns it.
  28296. */
  28297. SubMesh.prototype.render = function (enableAlphaMode) {
  28298. this._renderingMesh.render(this, enableAlphaMode);
  28299. return this;
  28300. };
  28301. /**
  28302. * Returns a new Index Buffer.
  28303. * Type returned : WebGLBuffer.
  28304. */
  28305. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28306. if (!this._linesIndexBuffer) {
  28307. var linesIndices = [];
  28308. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28309. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28310. }
  28311. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28312. this.linesIndexCount = linesIndices.length;
  28313. }
  28314. return this._linesIndexBuffer;
  28315. };
  28316. /**
  28317. * True is the passed Ray intersects the submesh bounding box.
  28318. * Boolean returned.
  28319. */
  28320. SubMesh.prototype.canIntersects = function (ray) {
  28321. var boundingInfo = this.getBoundingInfo();
  28322. if (!boundingInfo) {
  28323. return false;
  28324. }
  28325. return ray.intersectsBox(boundingInfo.boundingBox);
  28326. };
  28327. /**
  28328. * Returns an object IntersectionInfo.
  28329. */
  28330. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28331. var intersectInfo = null;
  28332. // LineMesh first as it's also a Mesh...
  28333. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28334. var lineMesh = this._mesh;
  28335. // Line test
  28336. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28337. var p0 = positions[indices[index]];
  28338. var p1 = positions[indices[index + 1]];
  28339. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28340. if (length < 0) {
  28341. continue;
  28342. }
  28343. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28344. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28345. if (fastCheck) {
  28346. break;
  28347. }
  28348. }
  28349. }
  28350. }
  28351. else {
  28352. // Triangles test
  28353. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28354. var p0 = positions[indices[index]];
  28355. var p1 = positions[indices[index + 1]];
  28356. var p2 = positions[indices[index + 2]];
  28357. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28358. if (currentIntersectInfo) {
  28359. if (currentIntersectInfo.distance < 0) {
  28360. continue;
  28361. }
  28362. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28363. intersectInfo = currentIntersectInfo;
  28364. intersectInfo.faceId = index / 3;
  28365. if (fastCheck) {
  28366. break;
  28367. }
  28368. }
  28369. }
  28370. }
  28371. }
  28372. return intersectInfo;
  28373. };
  28374. SubMesh.prototype._rebuild = function () {
  28375. if (this._linesIndexBuffer) {
  28376. this._linesIndexBuffer = null;
  28377. }
  28378. };
  28379. // Clone
  28380. /**
  28381. * Creates a new Submesh from the passed Mesh.
  28382. */
  28383. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28384. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28385. if (!this.IsGlobal) {
  28386. var boundingInfo = this.getBoundingInfo();
  28387. if (!boundingInfo) {
  28388. return result;
  28389. }
  28390. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28391. }
  28392. return result;
  28393. };
  28394. // Dispose
  28395. /**
  28396. * Disposes the Submesh.
  28397. * Returns nothing.
  28398. */
  28399. SubMesh.prototype.dispose = function () {
  28400. if (this._linesIndexBuffer) {
  28401. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28402. this._linesIndexBuffer = null;
  28403. }
  28404. // Remove from mesh
  28405. var index = this._mesh.subMeshes.indexOf(this);
  28406. this._mesh.subMeshes.splice(index, 1);
  28407. };
  28408. // Statics
  28409. /**
  28410. * Creates a new Submesh from the passed parameters :
  28411. * - materialIndex (integer) : the index of the main mesh material.
  28412. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28413. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28414. * - mesh (Mesh) : the main mesh to create the submesh from.
  28415. * - renderingMesh (optional Mesh) : rendering mesh.
  28416. */
  28417. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28418. var minVertexIndex = Number.MAX_VALUE;
  28419. var maxVertexIndex = -Number.MAX_VALUE;
  28420. renderingMesh = (renderingMesh || mesh);
  28421. var indices = renderingMesh.getIndices();
  28422. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28423. var vertexIndex = indices[index];
  28424. if (vertexIndex < minVertexIndex)
  28425. minVertexIndex = vertexIndex;
  28426. if (vertexIndex > maxVertexIndex)
  28427. maxVertexIndex = vertexIndex;
  28428. }
  28429. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28430. };
  28431. return SubMesh;
  28432. }(BaseSubMesh));
  28433. BABYLON.SubMesh = SubMesh;
  28434. })(BABYLON || (BABYLON = {}));
  28435. //# sourceMappingURL=babylon.subMesh.js.map
  28436. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28437. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28438. s = arguments[i];
  28439. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28440. t[p] = s[p];
  28441. }
  28442. return t;
  28443. };
  28444. var BABYLON;
  28445. (function (BABYLON) {
  28446. var MaterialDefines = /** @class */ (function () {
  28447. function MaterialDefines() {
  28448. this._isDirty = true;
  28449. this._areLightsDirty = true;
  28450. this._areAttributesDirty = true;
  28451. this._areTexturesDirty = true;
  28452. this._areFresnelDirty = true;
  28453. this._areMiscDirty = true;
  28454. this._areImageProcessingDirty = true;
  28455. this._normals = false;
  28456. this._uvs = false;
  28457. this._needNormals = false;
  28458. this._needUVs = false;
  28459. }
  28460. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28461. get: function () {
  28462. return this._isDirty;
  28463. },
  28464. enumerable: true,
  28465. configurable: true
  28466. });
  28467. MaterialDefines.prototype.markAsProcessed = function () {
  28468. this._isDirty = false;
  28469. this._areAttributesDirty = false;
  28470. this._areTexturesDirty = false;
  28471. this._areFresnelDirty = false;
  28472. this._areLightsDirty = false;
  28473. this._areMiscDirty = false;
  28474. this._areImageProcessingDirty = false;
  28475. };
  28476. MaterialDefines.prototype.markAsUnprocessed = function () {
  28477. this._isDirty = true;
  28478. };
  28479. MaterialDefines.prototype.markAllAsDirty = function () {
  28480. this._areTexturesDirty = true;
  28481. this._areAttributesDirty = true;
  28482. this._areLightsDirty = true;
  28483. this._areFresnelDirty = true;
  28484. this._areMiscDirty = true;
  28485. this._areImageProcessingDirty = true;
  28486. this._isDirty = true;
  28487. };
  28488. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28489. this._areImageProcessingDirty = true;
  28490. this._isDirty = true;
  28491. };
  28492. MaterialDefines.prototype.markAsLightDirty = function () {
  28493. this._areLightsDirty = true;
  28494. this._isDirty = true;
  28495. };
  28496. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28497. this._areAttributesDirty = true;
  28498. this._isDirty = true;
  28499. };
  28500. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28501. this._areTexturesDirty = true;
  28502. this._isDirty = true;
  28503. };
  28504. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28505. this._areFresnelDirty = true;
  28506. this._isDirty = true;
  28507. };
  28508. MaterialDefines.prototype.markAsMiscDirty = function () {
  28509. this._areMiscDirty = true;
  28510. this._isDirty = true;
  28511. };
  28512. MaterialDefines.prototype.rebuild = function () {
  28513. if (this._keys) {
  28514. delete this._keys;
  28515. }
  28516. this._keys = [];
  28517. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28518. var key = _a[_i];
  28519. if (key[0] === "_") {
  28520. continue;
  28521. }
  28522. this._keys.push(key);
  28523. }
  28524. };
  28525. MaterialDefines.prototype.isEqual = function (other) {
  28526. if (this._keys.length !== other._keys.length) {
  28527. return false;
  28528. }
  28529. for (var index = 0; index < this._keys.length; index++) {
  28530. var prop = this._keys[index];
  28531. if (this[prop] !== other[prop]) {
  28532. return false;
  28533. }
  28534. }
  28535. return true;
  28536. };
  28537. MaterialDefines.prototype.cloneTo = function (other) {
  28538. if (this._keys.length !== other._keys.length) {
  28539. other._keys = this._keys.slice(0);
  28540. }
  28541. for (var index = 0; index < this._keys.length; index++) {
  28542. var prop = this._keys[index];
  28543. other[prop] = this[prop];
  28544. }
  28545. };
  28546. MaterialDefines.prototype.reset = function () {
  28547. for (var index = 0; index < this._keys.length; index++) {
  28548. var prop = this._keys[index];
  28549. if (typeof (this[prop]) === "number") {
  28550. this[prop] = 0;
  28551. }
  28552. else {
  28553. this[prop] = false;
  28554. }
  28555. }
  28556. };
  28557. MaterialDefines.prototype.toString = function () {
  28558. var result = "";
  28559. for (var index = 0; index < this._keys.length; index++) {
  28560. var prop = this._keys[index];
  28561. var value = this[prop];
  28562. if (typeof (value) === "number") {
  28563. result += "#define " + prop + " " + this[prop] + "\n";
  28564. }
  28565. else if (value) {
  28566. result += "#define " + prop + "\n";
  28567. }
  28568. }
  28569. return result;
  28570. };
  28571. return MaterialDefines;
  28572. }());
  28573. BABYLON.MaterialDefines = MaterialDefines;
  28574. var Material = /** @class */ (function () {
  28575. function Material(name, scene, doNotAdd) {
  28576. this.checkReadyOnEveryCall = false;
  28577. this.checkReadyOnlyOnce = false;
  28578. this.state = "";
  28579. this.alpha = 1.0;
  28580. this._backFaceCulling = true;
  28581. this.doNotSerialize = false;
  28582. this.storeEffectOnSubMeshes = false;
  28583. /**
  28584. * An event triggered when the material is disposed.
  28585. * @type {BABYLON.Observable}
  28586. */
  28587. this.onDisposeObservable = new BABYLON.Observable();
  28588. /**
  28589. * An event triggered when the material is bound.
  28590. * @type {BABYLON.Observable}
  28591. */
  28592. this.onBindObservable = new BABYLON.Observable();
  28593. /**
  28594. * An event triggered when the material is unbound.
  28595. * @type {BABYLON.Observable}
  28596. */
  28597. this.onUnBindObservable = new BABYLON.Observable();
  28598. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28599. this._needDepthPrePass = false;
  28600. this.disableDepthWrite = false;
  28601. this.forceDepthWrite = false;
  28602. this.separateCullingPass = false;
  28603. this._fogEnabled = true;
  28604. this.pointSize = 1.0;
  28605. this.zOffset = 0;
  28606. this._wasPreviouslyReady = false;
  28607. this._fillMode = Material.TriangleFillMode;
  28608. this.name = name;
  28609. this.id = name || BABYLON.Tools.RandomId();
  28610. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28611. if (this._scene.useRightHandedSystem) {
  28612. this.sideOrientation = Material.ClockWiseSideOrientation;
  28613. }
  28614. else {
  28615. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28616. }
  28617. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28618. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28619. if (!doNotAdd) {
  28620. this._scene.materials.push(this);
  28621. }
  28622. }
  28623. Object.defineProperty(Material, "TriangleFillMode", {
  28624. get: function () {
  28625. return Material._TriangleFillMode;
  28626. },
  28627. enumerable: true,
  28628. configurable: true
  28629. });
  28630. Object.defineProperty(Material, "WireFrameFillMode", {
  28631. get: function () {
  28632. return Material._WireFrameFillMode;
  28633. },
  28634. enumerable: true,
  28635. configurable: true
  28636. });
  28637. Object.defineProperty(Material, "PointFillMode", {
  28638. get: function () {
  28639. return Material._PointFillMode;
  28640. },
  28641. enumerable: true,
  28642. configurable: true
  28643. });
  28644. Object.defineProperty(Material, "PointListDrawMode", {
  28645. get: function () {
  28646. return Material._PointListDrawMode;
  28647. },
  28648. enumerable: true,
  28649. configurable: true
  28650. });
  28651. Object.defineProperty(Material, "LineListDrawMode", {
  28652. get: function () {
  28653. return Material._LineListDrawMode;
  28654. },
  28655. enumerable: true,
  28656. configurable: true
  28657. });
  28658. Object.defineProperty(Material, "LineLoopDrawMode", {
  28659. get: function () {
  28660. return Material._LineLoopDrawMode;
  28661. },
  28662. enumerable: true,
  28663. configurable: true
  28664. });
  28665. Object.defineProperty(Material, "LineStripDrawMode", {
  28666. get: function () {
  28667. return Material._LineStripDrawMode;
  28668. },
  28669. enumerable: true,
  28670. configurable: true
  28671. });
  28672. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28673. get: function () {
  28674. return Material._TriangleStripDrawMode;
  28675. },
  28676. enumerable: true,
  28677. configurable: true
  28678. });
  28679. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28680. get: function () {
  28681. return Material._TriangleFanDrawMode;
  28682. },
  28683. enumerable: true,
  28684. configurable: true
  28685. });
  28686. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28687. get: function () {
  28688. return Material._ClockWiseSideOrientation;
  28689. },
  28690. enumerable: true,
  28691. configurable: true
  28692. });
  28693. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28694. get: function () {
  28695. return Material._CounterClockWiseSideOrientation;
  28696. },
  28697. enumerable: true,
  28698. configurable: true
  28699. });
  28700. Object.defineProperty(Material, "TextureDirtyFlag", {
  28701. get: function () {
  28702. return Material._TextureDirtyFlag;
  28703. },
  28704. enumerable: true,
  28705. configurable: true
  28706. });
  28707. Object.defineProperty(Material, "LightDirtyFlag", {
  28708. get: function () {
  28709. return Material._LightDirtyFlag;
  28710. },
  28711. enumerable: true,
  28712. configurable: true
  28713. });
  28714. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28715. get: function () {
  28716. return Material._FresnelDirtyFlag;
  28717. },
  28718. enumerable: true,
  28719. configurable: true
  28720. });
  28721. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28722. get: function () {
  28723. return Material._AttributesDirtyFlag;
  28724. },
  28725. enumerable: true,
  28726. configurable: true
  28727. });
  28728. Object.defineProperty(Material, "MiscDirtyFlag", {
  28729. get: function () {
  28730. return Material._MiscDirtyFlag;
  28731. },
  28732. enumerable: true,
  28733. configurable: true
  28734. });
  28735. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28736. get: function () {
  28737. return this._backFaceCulling;
  28738. },
  28739. set: function (value) {
  28740. if (this._backFaceCulling === value) {
  28741. return;
  28742. }
  28743. this._backFaceCulling = value;
  28744. this.markAsDirty(Material.TextureDirtyFlag);
  28745. },
  28746. enumerable: true,
  28747. configurable: true
  28748. });
  28749. Object.defineProperty(Material.prototype, "onDispose", {
  28750. set: function (callback) {
  28751. if (this._onDisposeObserver) {
  28752. this.onDisposeObservable.remove(this._onDisposeObserver);
  28753. }
  28754. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28755. },
  28756. enumerable: true,
  28757. configurable: true
  28758. });
  28759. Object.defineProperty(Material.prototype, "onBind", {
  28760. set: function (callback) {
  28761. if (this._onBindObserver) {
  28762. this.onBindObservable.remove(this._onBindObserver);
  28763. }
  28764. this._onBindObserver = this.onBindObservable.add(callback);
  28765. },
  28766. enumerable: true,
  28767. configurable: true
  28768. });
  28769. Object.defineProperty(Material.prototype, "alphaMode", {
  28770. get: function () {
  28771. return this._alphaMode;
  28772. },
  28773. set: function (value) {
  28774. if (this._alphaMode === value) {
  28775. return;
  28776. }
  28777. this._alphaMode = value;
  28778. this.markAsDirty(Material.TextureDirtyFlag);
  28779. },
  28780. enumerable: true,
  28781. configurable: true
  28782. });
  28783. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28784. get: function () {
  28785. return this._needDepthPrePass;
  28786. },
  28787. set: function (value) {
  28788. if (this._needDepthPrePass === value) {
  28789. return;
  28790. }
  28791. this._needDepthPrePass = value;
  28792. if (this._needDepthPrePass) {
  28793. this.checkReadyOnEveryCall = true;
  28794. }
  28795. },
  28796. enumerable: true,
  28797. configurable: true
  28798. });
  28799. Object.defineProperty(Material.prototype, "fogEnabled", {
  28800. get: function () {
  28801. return this._fogEnabled;
  28802. },
  28803. set: function (value) {
  28804. if (this._fogEnabled === value) {
  28805. return;
  28806. }
  28807. this._fogEnabled = value;
  28808. this.markAsDirty(Material.MiscDirtyFlag);
  28809. },
  28810. enumerable: true,
  28811. configurable: true
  28812. });
  28813. Object.defineProperty(Material.prototype, "wireframe", {
  28814. get: function () {
  28815. return this._fillMode === Material.WireFrameFillMode;
  28816. },
  28817. set: function (value) {
  28818. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28819. },
  28820. enumerable: true,
  28821. configurable: true
  28822. });
  28823. Object.defineProperty(Material.prototype, "pointsCloud", {
  28824. get: function () {
  28825. return this._fillMode === Material.PointFillMode;
  28826. },
  28827. set: function (value) {
  28828. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28829. },
  28830. enumerable: true,
  28831. configurable: true
  28832. });
  28833. Object.defineProperty(Material.prototype, "fillMode", {
  28834. get: function () {
  28835. return this._fillMode;
  28836. },
  28837. set: function (value) {
  28838. if (this._fillMode === value) {
  28839. return;
  28840. }
  28841. this._fillMode = value;
  28842. this.markAsDirty(Material.MiscDirtyFlag);
  28843. },
  28844. enumerable: true,
  28845. configurable: true
  28846. });
  28847. /**
  28848. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28849. * subclasses should override adding information pertainent to themselves
  28850. */
  28851. Material.prototype.toString = function (fullDetails) {
  28852. var ret = "Name: " + this.name;
  28853. if (fullDetails) {
  28854. }
  28855. return ret;
  28856. };
  28857. /**
  28858. * Child classes can use it to update shaders
  28859. */
  28860. Material.prototype.getClassName = function () {
  28861. return "Material";
  28862. };
  28863. Object.defineProperty(Material.prototype, "isFrozen", {
  28864. get: function () {
  28865. return this.checkReadyOnlyOnce;
  28866. },
  28867. enumerable: true,
  28868. configurable: true
  28869. });
  28870. Material.prototype.freeze = function () {
  28871. this.checkReadyOnlyOnce = true;
  28872. };
  28873. Material.prototype.unfreeze = function () {
  28874. this.checkReadyOnlyOnce = false;
  28875. };
  28876. Material.prototype.isReady = function (mesh, useInstances) {
  28877. return true;
  28878. };
  28879. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28880. return false;
  28881. };
  28882. Material.prototype.getEffect = function () {
  28883. return this._effect;
  28884. };
  28885. Material.prototype.getScene = function () {
  28886. return this._scene;
  28887. };
  28888. Material.prototype.needAlphaBlending = function () {
  28889. return (this.alpha < 1.0);
  28890. };
  28891. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28892. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28893. };
  28894. Material.prototype.needAlphaTesting = function () {
  28895. return false;
  28896. };
  28897. Material.prototype.getAlphaTestTexture = function () {
  28898. return null;
  28899. };
  28900. Material.prototype.markDirty = function () {
  28901. this._wasPreviouslyReady = false;
  28902. };
  28903. Material.prototype._preBind = function (effect, overrideOrientation) {
  28904. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28905. var engine = this._scene.getEngine();
  28906. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28907. var reverse = orientation === Material.ClockWiseSideOrientation;
  28908. engine.enableEffect(effect ? effect : this._effect);
  28909. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28910. return reverse;
  28911. };
  28912. Material.prototype.bind = function (world, mesh) {
  28913. };
  28914. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28915. };
  28916. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28917. };
  28918. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28919. sceneUbo.bindToEffect(effect, "Scene");
  28920. };
  28921. Material.prototype.bindView = function (effect) {
  28922. if (!this._useUBO) {
  28923. effect.setMatrix("view", this.getScene().getViewMatrix());
  28924. }
  28925. else {
  28926. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28927. }
  28928. };
  28929. Material.prototype.bindViewProjection = function (effect) {
  28930. if (!this._useUBO) {
  28931. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28932. }
  28933. else {
  28934. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28935. }
  28936. };
  28937. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  28938. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  28939. };
  28940. Material.prototype._afterBind = function (mesh) {
  28941. this._scene._cachedMaterial = this;
  28942. if (mesh) {
  28943. this._scene._cachedVisibility = mesh.visibility;
  28944. }
  28945. else {
  28946. this._scene._cachedVisibility = 1;
  28947. }
  28948. if (mesh) {
  28949. this.onBindObservable.notifyObservers(mesh);
  28950. }
  28951. if (this.disableDepthWrite) {
  28952. var engine = this._scene.getEngine();
  28953. this._cachedDepthWriteState = engine.getDepthWrite();
  28954. engine.setDepthWrite(false);
  28955. }
  28956. };
  28957. Material.prototype.unbind = function () {
  28958. this.onUnBindObservable.notifyObservers(this);
  28959. if (this.disableDepthWrite) {
  28960. var engine = this._scene.getEngine();
  28961. engine.setDepthWrite(this._cachedDepthWriteState);
  28962. }
  28963. };
  28964. Material.prototype.getActiveTextures = function () {
  28965. return [];
  28966. };
  28967. Material.prototype.hasTexture = function (texture) {
  28968. return false;
  28969. };
  28970. Material.prototype.clone = function (name) {
  28971. return null;
  28972. };
  28973. Material.prototype.getBindedMeshes = function () {
  28974. var result = new Array();
  28975. for (var index = 0; index < this._scene.meshes.length; index++) {
  28976. var mesh = this._scene.meshes[index];
  28977. if (mesh.material === this) {
  28978. result.push(mesh);
  28979. }
  28980. }
  28981. return result;
  28982. };
  28983. /**
  28984. * Force shader compilation including textures ready check
  28985. */
  28986. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28987. var _this = this;
  28988. var localOptions = __assign({ clipPlane: false }, options);
  28989. var subMesh = new BABYLON.BaseSubMesh();
  28990. var scene = this.getScene();
  28991. var checkReady = function () {
  28992. if (!_this._scene || !_this._scene.getEngine()) {
  28993. return;
  28994. }
  28995. if (subMesh._materialDefines) {
  28996. subMesh._materialDefines._renderId = -1;
  28997. }
  28998. var clipPlaneState = scene.clipPlane;
  28999. if (localOptions.clipPlane) {
  29000. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29001. }
  29002. if (_this.storeEffectOnSubMeshes) {
  29003. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29004. if (onCompiled) {
  29005. onCompiled(_this);
  29006. }
  29007. }
  29008. else {
  29009. setTimeout(checkReady, 16);
  29010. }
  29011. }
  29012. else {
  29013. if (_this.isReady(mesh)) {
  29014. if (onCompiled) {
  29015. onCompiled(_this);
  29016. }
  29017. }
  29018. else {
  29019. setTimeout(checkReady, 16);
  29020. }
  29021. }
  29022. if (options && options.clipPlane) {
  29023. scene.clipPlane = clipPlaneState;
  29024. }
  29025. };
  29026. checkReady();
  29027. };
  29028. Material.prototype.markAsDirty = function (flag) {
  29029. if (flag & Material.TextureDirtyFlag) {
  29030. this._markAllSubMeshesAsTexturesDirty();
  29031. }
  29032. if (flag & Material.LightDirtyFlag) {
  29033. this._markAllSubMeshesAsLightsDirty();
  29034. }
  29035. if (flag & Material.FresnelDirtyFlag) {
  29036. this._markAllSubMeshesAsFresnelDirty();
  29037. }
  29038. if (flag & Material.AttributesDirtyFlag) {
  29039. this._markAllSubMeshesAsAttributesDirty();
  29040. }
  29041. if (flag & Material.MiscDirtyFlag) {
  29042. this._markAllSubMeshesAsMiscDirty();
  29043. }
  29044. this.getScene().resetCachedMaterial();
  29045. };
  29046. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29047. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29048. var mesh = _a[_i];
  29049. if (!mesh.subMeshes) {
  29050. continue;
  29051. }
  29052. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29053. var subMesh = _c[_b];
  29054. if (subMesh.getMaterial() !== this) {
  29055. continue;
  29056. }
  29057. if (!subMesh._materialDefines) {
  29058. continue;
  29059. }
  29060. func(subMesh._materialDefines);
  29061. }
  29062. }
  29063. };
  29064. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29065. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29066. };
  29067. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29068. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29069. };
  29070. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29071. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29072. };
  29073. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29074. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29075. };
  29076. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29077. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29078. };
  29079. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29080. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29081. };
  29082. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29083. // Animations
  29084. this.getScene().stopAnimation(this);
  29085. // Remove from scene
  29086. var index = this._scene.materials.indexOf(this);
  29087. if (index >= 0) {
  29088. this._scene.materials.splice(index, 1);
  29089. }
  29090. // Remove from meshes
  29091. for (index = 0; index < this._scene.meshes.length; index++) {
  29092. var mesh = this._scene.meshes[index];
  29093. if (mesh.material === this) {
  29094. mesh.material = null;
  29095. if (mesh.geometry) {
  29096. var geometry = (mesh.geometry);
  29097. if (this.storeEffectOnSubMeshes) {
  29098. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29099. var subMesh = _a[_i];
  29100. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29101. if (forceDisposeEffect && subMesh._materialEffect) {
  29102. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29103. }
  29104. }
  29105. }
  29106. else {
  29107. geometry._releaseVertexArrayObject(this._effect);
  29108. }
  29109. }
  29110. }
  29111. }
  29112. this._uniformBuffer.dispose();
  29113. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29114. if (forceDisposeEffect && this._effect) {
  29115. if (!this.storeEffectOnSubMeshes) {
  29116. this._scene.getEngine()._releaseEffect(this._effect);
  29117. }
  29118. this._effect = null;
  29119. }
  29120. // Callback
  29121. this.onDisposeObservable.notifyObservers(this);
  29122. this.onDisposeObservable.clear();
  29123. this.onBindObservable.clear();
  29124. this.onUnBindObservable.clear();
  29125. };
  29126. Material.prototype.serialize = function () {
  29127. return BABYLON.SerializationHelper.Serialize(this);
  29128. };
  29129. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29130. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29131. multiMaterial.id = parsedMultiMaterial.id;
  29132. if (BABYLON.Tags) {
  29133. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29134. }
  29135. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29136. var subMatId = parsedMultiMaterial.materials[matIndex];
  29137. if (subMatId) {
  29138. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29139. }
  29140. else {
  29141. multiMaterial.subMaterials.push(null);
  29142. }
  29143. }
  29144. return multiMaterial;
  29145. };
  29146. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29147. if (!parsedMaterial.customType) {
  29148. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29149. }
  29150. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29151. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29152. if (!BABYLON.LegacyPBRMaterial) {
  29153. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29154. return;
  29155. }
  29156. }
  29157. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29158. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29159. ;
  29160. };
  29161. // Triangle views
  29162. Material._TriangleFillMode = 0;
  29163. Material._WireFrameFillMode = 1;
  29164. Material._PointFillMode = 2;
  29165. // Draw modes
  29166. Material._PointListDrawMode = 3;
  29167. Material._LineListDrawMode = 4;
  29168. Material._LineLoopDrawMode = 5;
  29169. Material._LineStripDrawMode = 6;
  29170. Material._TriangleStripDrawMode = 7;
  29171. Material._TriangleFanDrawMode = 8;
  29172. Material._ClockWiseSideOrientation = 0;
  29173. Material._CounterClockWiseSideOrientation = 1;
  29174. Material._TextureDirtyFlag = 1;
  29175. Material._LightDirtyFlag = 2;
  29176. Material._FresnelDirtyFlag = 4;
  29177. Material._AttributesDirtyFlag = 8;
  29178. Material._MiscDirtyFlag = 16;
  29179. __decorate([
  29180. BABYLON.serialize()
  29181. ], Material.prototype, "id", void 0);
  29182. __decorate([
  29183. BABYLON.serialize()
  29184. ], Material.prototype, "name", void 0);
  29185. __decorate([
  29186. BABYLON.serialize()
  29187. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29188. __decorate([
  29189. BABYLON.serialize()
  29190. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29191. __decorate([
  29192. BABYLON.serialize()
  29193. ], Material.prototype, "state", void 0);
  29194. __decorate([
  29195. BABYLON.serialize()
  29196. ], Material.prototype, "alpha", void 0);
  29197. __decorate([
  29198. BABYLON.serialize("backFaceCulling")
  29199. ], Material.prototype, "_backFaceCulling", void 0);
  29200. __decorate([
  29201. BABYLON.serialize()
  29202. ], Material.prototype, "sideOrientation", void 0);
  29203. __decorate([
  29204. BABYLON.serialize("alphaMode")
  29205. ], Material.prototype, "_alphaMode", void 0);
  29206. __decorate([
  29207. BABYLON.serialize()
  29208. ], Material.prototype, "_needDepthPrePass", void 0);
  29209. __decorate([
  29210. BABYLON.serialize()
  29211. ], Material.prototype, "disableDepthWrite", void 0);
  29212. __decorate([
  29213. BABYLON.serialize()
  29214. ], Material.prototype, "forceDepthWrite", void 0);
  29215. __decorate([
  29216. BABYLON.serialize()
  29217. ], Material.prototype, "separateCullingPass", void 0);
  29218. __decorate([
  29219. BABYLON.serialize("fogEnabled")
  29220. ], Material.prototype, "_fogEnabled", void 0);
  29221. __decorate([
  29222. BABYLON.serialize()
  29223. ], Material.prototype, "pointSize", void 0);
  29224. __decorate([
  29225. BABYLON.serialize()
  29226. ], Material.prototype, "zOffset", void 0);
  29227. __decorate([
  29228. BABYLON.serialize()
  29229. ], Material.prototype, "wireframe", null);
  29230. __decorate([
  29231. BABYLON.serialize()
  29232. ], Material.prototype, "pointsCloud", null);
  29233. __decorate([
  29234. BABYLON.serialize()
  29235. ], Material.prototype, "fillMode", null);
  29236. return Material;
  29237. }());
  29238. BABYLON.Material = Material;
  29239. })(BABYLON || (BABYLON = {}));
  29240. //# sourceMappingURL=babylon.material.js.map
  29241. var BABYLON;
  29242. (function (BABYLON) {
  29243. var UniformBuffer = /** @class */ (function () {
  29244. /**
  29245. * Uniform buffer objects.
  29246. *
  29247. * Handles blocks of uniform on the GPU.
  29248. *
  29249. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29250. *
  29251. * For more information, please refer to :
  29252. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29253. */
  29254. function UniformBuffer(engine, data, dynamic) {
  29255. this._engine = engine;
  29256. this._noUBO = !engine.supportsUniformBuffers;
  29257. this._dynamic = dynamic;
  29258. this._data = data || [];
  29259. this._uniformLocations = {};
  29260. this._uniformSizes = {};
  29261. this._uniformLocationPointer = 0;
  29262. this._needSync = false;
  29263. if (this._noUBO) {
  29264. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29265. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29266. this.updateFloat = this._updateFloatForEffect;
  29267. this.updateFloat2 = this._updateFloat2ForEffect;
  29268. this.updateFloat3 = this._updateFloat3ForEffect;
  29269. this.updateFloat4 = this._updateFloat4ForEffect;
  29270. this.updateMatrix = this._updateMatrixForEffect;
  29271. this.updateVector3 = this._updateVector3ForEffect;
  29272. this.updateVector4 = this._updateVector4ForEffect;
  29273. this.updateColor3 = this._updateColor3ForEffect;
  29274. this.updateColor4 = this._updateColor4ForEffect;
  29275. }
  29276. else {
  29277. this._engine._uniformBuffers.push(this);
  29278. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29279. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29280. this.updateFloat = this._updateFloatForUniform;
  29281. this.updateFloat2 = this._updateFloat2ForUniform;
  29282. this.updateFloat3 = this._updateFloat3ForUniform;
  29283. this.updateFloat4 = this._updateFloat4ForUniform;
  29284. this.updateMatrix = this._updateMatrixForUniform;
  29285. this.updateVector3 = this._updateVector3ForUniform;
  29286. this.updateVector4 = this._updateVector4ForUniform;
  29287. this.updateColor3 = this._updateColor3ForUniform;
  29288. this.updateColor4 = this._updateColor4ForUniform;
  29289. }
  29290. }
  29291. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29292. // Properties
  29293. /**
  29294. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29295. * or just falling back on setUniformXXX calls.
  29296. */
  29297. get: function () {
  29298. return !this._noUBO;
  29299. },
  29300. enumerable: true,
  29301. configurable: true
  29302. });
  29303. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29304. /**
  29305. * Indicates if the WebGL underlying uniform buffer is in sync
  29306. * with the javascript cache data.
  29307. */
  29308. get: function () {
  29309. return !this._needSync;
  29310. },
  29311. enumerable: true,
  29312. configurable: true
  29313. });
  29314. /**
  29315. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29316. * Also, a dynamic UniformBuffer will disable cache verification and always
  29317. * update the underlying WebGL uniform buffer to the GPU.
  29318. */
  29319. UniformBuffer.prototype.isDynamic = function () {
  29320. return this._dynamic !== undefined;
  29321. };
  29322. /**
  29323. * The data cache on JS side.
  29324. */
  29325. UniformBuffer.prototype.getData = function () {
  29326. return this._bufferData;
  29327. };
  29328. /**
  29329. * The underlying WebGL Uniform buffer.
  29330. */
  29331. UniformBuffer.prototype.getBuffer = function () {
  29332. return this._buffer;
  29333. };
  29334. /**
  29335. * std140 layout specifies how to align data within an UBO structure.
  29336. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29337. * for specs.
  29338. */
  29339. UniformBuffer.prototype._fillAlignment = function (size) {
  29340. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29341. // and 4x4 matrices
  29342. // TODO : change if other types are used
  29343. var alignment;
  29344. if (size <= 2) {
  29345. alignment = size;
  29346. }
  29347. else {
  29348. alignment = 4;
  29349. }
  29350. if ((this._uniformLocationPointer % alignment) !== 0) {
  29351. var oldPointer = this._uniformLocationPointer;
  29352. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29353. var diff = this._uniformLocationPointer - oldPointer;
  29354. for (var i = 0; i < diff; i++) {
  29355. this._data.push(0);
  29356. }
  29357. }
  29358. };
  29359. /**
  29360. * Adds an uniform in the buffer.
  29361. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29362. * for the layout to be correct !
  29363. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29364. * @param {number|number[]} size Data size, or data directly.
  29365. */
  29366. UniformBuffer.prototype.addUniform = function (name, size) {
  29367. if (this._noUBO) {
  29368. return;
  29369. }
  29370. if (this._uniformLocations[name] !== undefined) {
  29371. // Already existing uniform
  29372. return;
  29373. }
  29374. // This function must be called in the order of the shader layout !
  29375. // size can be the size of the uniform, or data directly
  29376. var data;
  29377. if (size instanceof Array) {
  29378. data = size;
  29379. size = data.length;
  29380. }
  29381. else {
  29382. size = size;
  29383. data = [];
  29384. // Fill with zeros
  29385. for (var i = 0; i < size; i++) {
  29386. data.push(0);
  29387. }
  29388. }
  29389. this._fillAlignment(size);
  29390. this._uniformSizes[name] = size;
  29391. this._uniformLocations[name] = this._uniformLocationPointer;
  29392. this._uniformLocationPointer += size;
  29393. for (var i = 0; i < size; i++) {
  29394. this._data.push(data[i]);
  29395. }
  29396. this._needSync = true;
  29397. };
  29398. /**
  29399. * Wrapper for addUniform.
  29400. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29401. * @param {Matrix} mat A 4x4 matrix.
  29402. */
  29403. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29404. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29405. };
  29406. /**
  29407. * Wrapper for addUniform.
  29408. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29409. * @param {number} x
  29410. * @param {number} y
  29411. */
  29412. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29413. var temp = [x, y];
  29414. this.addUniform(name, temp);
  29415. };
  29416. /**
  29417. * Wrapper for addUniform.
  29418. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29419. * @param {number} x
  29420. * @param {number} y
  29421. * @param {number} z
  29422. */
  29423. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29424. var temp = [x, y, z];
  29425. this.addUniform(name, temp);
  29426. };
  29427. /**
  29428. * Wrapper for addUniform.
  29429. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29430. * @param {Color3} color
  29431. */
  29432. UniformBuffer.prototype.addColor3 = function (name, color) {
  29433. var temp = new Array();
  29434. color.toArray(temp);
  29435. this.addUniform(name, temp);
  29436. };
  29437. /**
  29438. * Wrapper for addUniform.
  29439. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29440. * @param {Color3} color
  29441. * @param {number} alpha
  29442. */
  29443. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29444. var temp = new Array();
  29445. color.toArray(temp);
  29446. temp.push(alpha);
  29447. this.addUniform(name, temp);
  29448. };
  29449. /**
  29450. * Wrapper for addUniform.
  29451. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29452. * @param {Vector3} vector
  29453. */
  29454. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29455. var temp = new Array();
  29456. vector.toArray(temp);
  29457. this.addUniform(name, temp);
  29458. };
  29459. /**
  29460. * Wrapper for addUniform.
  29461. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29462. */
  29463. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29464. this.addUniform(name, 12);
  29465. };
  29466. /**
  29467. * Wrapper for addUniform.
  29468. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29469. */
  29470. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29471. this.addUniform(name, 8);
  29472. };
  29473. /**
  29474. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29475. */
  29476. UniformBuffer.prototype.create = function () {
  29477. if (this._noUBO) {
  29478. return;
  29479. }
  29480. if (this._buffer) {
  29481. return; // nothing to do
  29482. }
  29483. // See spec, alignment must be filled as a vec4
  29484. this._fillAlignment(4);
  29485. this._bufferData = new Float32Array(this._data);
  29486. this._rebuild();
  29487. this._needSync = true;
  29488. };
  29489. UniformBuffer.prototype._rebuild = function () {
  29490. if (this._noUBO) {
  29491. return;
  29492. }
  29493. if (this._dynamic) {
  29494. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29495. }
  29496. else {
  29497. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29498. }
  29499. };
  29500. /**
  29501. * Updates the WebGL Uniform Buffer on the GPU.
  29502. * If the `dynamic` flag is set to true, no cache comparison is done.
  29503. * Otherwise, the buffer will be updated only if the cache differs.
  29504. */
  29505. UniformBuffer.prototype.update = function () {
  29506. if (!this._buffer) {
  29507. this.create();
  29508. return;
  29509. }
  29510. if (!this._dynamic && !this._needSync) {
  29511. return;
  29512. }
  29513. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29514. this._needSync = false;
  29515. };
  29516. /**
  29517. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29518. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29519. * @param {number[]|Float32Array} data Flattened data
  29520. * @param {number} size Size of the data.
  29521. */
  29522. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29523. var location = this._uniformLocations[uniformName];
  29524. if (location === undefined) {
  29525. if (this._buffer) {
  29526. // Cannot add an uniform if the buffer is already created
  29527. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29528. return;
  29529. }
  29530. this.addUniform(uniformName, size);
  29531. location = this._uniformLocations[uniformName];
  29532. }
  29533. if (!this._buffer) {
  29534. this.create();
  29535. }
  29536. if (!this._dynamic) {
  29537. // Cache for static uniform buffers
  29538. var changed = false;
  29539. for (var i = 0; i < size; i++) {
  29540. if (this._bufferData[location + i] !== data[i]) {
  29541. changed = true;
  29542. this._bufferData[location + i] = data[i];
  29543. }
  29544. }
  29545. this._needSync = this._needSync || changed;
  29546. }
  29547. else {
  29548. // No cache for dynamic
  29549. for (var i = 0; i < size; i++) {
  29550. this._bufferData[location + i] = data[i];
  29551. }
  29552. }
  29553. };
  29554. // Update methods
  29555. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29556. // To match std140, matrix must be realigned
  29557. for (var i = 0; i < 3; i++) {
  29558. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29559. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29560. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29561. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29562. }
  29563. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29564. };
  29565. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29566. this._currentEffect.setMatrix3x3(name, matrix);
  29567. };
  29568. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29569. this._currentEffect.setMatrix2x2(name, matrix);
  29570. };
  29571. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29572. // To match std140, matrix must be realigned
  29573. for (var i = 0; i < 2; i++) {
  29574. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29575. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29576. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29577. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29578. }
  29579. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29580. };
  29581. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29582. this._currentEffect.setFloat(name, x);
  29583. };
  29584. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29585. UniformBuffer._tempBuffer[0] = x;
  29586. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29587. };
  29588. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29589. if (suffix === void 0) { suffix = ""; }
  29590. this._currentEffect.setFloat2(name + suffix, x, y);
  29591. };
  29592. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29593. if (suffix === void 0) { suffix = ""; }
  29594. UniformBuffer._tempBuffer[0] = x;
  29595. UniformBuffer._tempBuffer[1] = y;
  29596. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29597. };
  29598. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29599. if (suffix === void 0) { suffix = ""; }
  29600. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29601. };
  29602. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29603. if (suffix === void 0) { suffix = ""; }
  29604. UniformBuffer._tempBuffer[0] = x;
  29605. UniformBuffer._tempBuffer[1] = y;
  29606. UniformBuffer._tempBuffer[2] = z;
  29607. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29608. };
  29609. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29610. if (suffix === void 0) { suffix = ""; }
  29611. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29612. };
  29613. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29614. if (suffix === void 0) { suffix = ""; }
  29615. UniformBuffer._tempBuffer[0] = x;
  29616. UniformBuffer._tempBuffer[1] = y;
  29617. UniformBuffer._tempBuffer[2] = z;
  29618. UniformBuffer._tempBuffer[3] = w;
  29619. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29620. };
  29621. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29622. this._currentEffect.setMatrix(name, mat);
  29623. };
  29624. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29625. this.updateUniform(name, mat.toArray(), 16);
  29626. };
  29627. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29628. this._currentEffect.setVector3(name, vector);
  29629. };
  29630. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29631. vector.toArray(UniformBuffer._tempBuffer);
  29632. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29633. };
  29634. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29635. this._currentEffect.setVector4(name, vector);
  29636. };
  29637. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29638. vector.toArray(UniformBuffer._tempBuffer);
  29639. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29640. };
  29641. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29642. if (suffix === void 0) { suffix = ""; }
  29643. this._currentEffect.setColor3(name + suffix, color);
  29644. };
  29645. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29646. if (suffix === void 0) { suffix = ""; }
  29647. color.toArray(UniformBuffer._tempBuffer);
  29648. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29649. };
  29650. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29651. if (suffix === void 0) { suffix = ""; }
  29652. this._currentEffect.setColor4(name + suffix, color, alpha);
  29653. };
  29654. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29655. if (suffix === void 0) { suffix = ""; }
  29656. color.toArray(UniformBuffer._tempBuffer);
  29657. UniformBuffer._tempBuffer[3] = alpha;
  29658. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29659. };
  29660. /**
  29661. * Sets a sampler uniform on the effect.
  29662. * @param {string} name Name of the sampler.
  29663. * @param {Texture} texture
  29664. */
  29665. UniformBuffer.prototype.setTexture = function (name, texture) {
  29666. this._currentEffect.setTexture(name, texture);
  29667. };
  29668. /**
  29669. * Directly updates the value of the uniform in the cache AND on the GPU.
  29670. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29671. * @param {number[]|Float32Array} data Flattened data
  29672. */
  29673. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29674. this.updateUniform(uniformName, data, data.length);
  29675. this.update();
  29676. };
  29677. /**
  29678. * Binds this uniform buffer to an effect.
  29679. * @param {Effect} effect
  29680. * @param {string} name Name of the uniform block in the shader.
  29681. */
  29682. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29683. this._currentEffect = effect;
  29684. if (this._noUBO || !this._buffer) {
  29685. return;
  29686. }
  29687. effect.bindUniformBuffer(this._buffer, name);
  29688. };
  29689. /**
  29690. * Disposes the uniform buffer.
  29691. */
  29692. UniformBuffer.prototype.dispose = function () {
  29693. if (this._noUBO) {
  29694. return;
  29695. }
  29696. var index = this._engine._uniformBuffers.indexOf(this);
  29697. if (index !== -1) {
  29698. this._engine._uniformBuffers.splice(index, 1);
  29699. }
  29700. if (!this._buffer) {
  29701. return;
  29702. }
  29703. if (this._engine._releaseBuffer(this._buffer)) {
  29704. this._buffer = null;
  29705. }
  29706. };
  29707. // Pool for avoiding memory leaks
  29708. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29709. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29710. return UniformBuffer;
  29711. }());
  29712. BABYLON.UniformBuffer = UniformBuffer;
  29713. })(BABYLON || (BABYLON = {}));
  29714. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29715. var BABYLON;
  29716. (function (BABYLON) {
  29717. var VertexData = /** @class */ (function () {
  29718. function VertexData() {
  29719. }
  29720. VertexData.prototype.set = function (data, kind) {
  29721. switch (kind) {
  29722. case BABYLON.VertexBuffer.PositionKind:
  29723. this.positions = data;
  29724. break;
  29725. case BABYLON.VertexBuffer.NormalKind:
  29726. this.normals = data;
  29727. break;
  29728. case BABYLON.VertexBuffer.TangentKind:
  29729. this.tangents = data;
  29730. break;
  29731. case BABYLON.VertexBuffer.UVKind:
  29732. this.uvs = data;
  29733. break;
  29734. case BABYLON.VertexBuffer.UV2Kind:
  29735. this.uvs2 = data;
  29736. break;
  29737. case BABYLON.VertexBuffer.UV3Kind:
  29738. this.uvs3 = data;
  29739. break;
  29740. case BABYLON.VertexBuffer.UV4Kind:
  29741. this.uvs4 = data;
  29742. break;
  29743. case BABYLON.VertexBuffer.UV5Kind:
  29744. this.uvs5 = data;
  29745. break;
  29746. case BABYLON.VertexBuffer.UV6Kind:
  29747. this.uvs6 = data;
  29748. break;
  29749. case BABYLON.VertexBuffer.ColorKind:
  29750. this.colors = data;
  29751. break;
  29752. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29753. this.matricesIndices = data;
  29754. break;
  29755. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29756. this.matricesWeights = data;
  29757. break;
  29758. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29759. this.matricesIndicesExtra = data;
  29760. break;
  29761. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29762. this.matricesWeightsExtra = data;
  29763. break;
  29764. }
  29765. };
  29766. /**
  29767. * Associates the vertexData to the passed Mesh.
  29768. * Sets it as updatable or not (default `false`).
  29769. * Returns the VertexData.
  29770. */
  29771. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29772. this._applyTo(mesh, updatable);
  29773. return this;
  29774. };
  29775. /**
  29776. * Associates the vertexData to the passed Geometry.
  29777. * Sets it as updatable or not (default `false`).
  29778. * Returns the VertexData.
  29779. */
  29780. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29781. this._applyTo(geometry, updatable);
  29782. return this;
  29783. };
  29784. /**
  29785. * Updates the associated mesh.
  29786. * Returns the VertexData.
  29787. */
  29788. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29789. this._update(mesh);
  29790. return this;
  29791. };
  29792. /**
  29793. * Updates the associated geometry.
  29794. * Returns the VertexData.
  29795. */
  29796. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29797. this._update(geometry);
  29798. return this;
  29799. };
  29800. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29801. if (updatable === void 0) { updatable = false; }
  29802. if (this.positions) {
  29803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29804. }
  29805. if (this.normals) {
  29806. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29807. }
  29808. if (this.tangents) {
  29809. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29810. }
  29811. if (this.uvs) {
  29812. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29813. }
  29814. if (this.uvs2) {
  29815. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29816. }
  29817. if (this.uvs3) {
  29818. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29819. }
  29820. if (this.uvs4) {
  29821. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29822. }
  29823. if (this.uvs5) {
  29824. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29825. }
  29826. if (this.uvs6) {
  29827. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29828. }
  29829. if (this.colors) {
  29830. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29831. }
  29832. if (this.matricesIndices) {
  29833. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29834. }
  29835. if (this.matricesWeights) {
  29836. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29837. }
  29838. if (this.matricesIndicesExtra) {
  29839. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29840. }
  29841. if (this.matricesWeightsExtra) {
  29842. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29843. }
  29844. if (this.indices) {
  29845. meshOrGeometry.setIndices(this.indices, null, updatable);
  29846. }
  29847. return this;
  29848. };
  29849. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29850. if (this.positions) {
  29851. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29852. }
  29853. if (this.normals) {
  29854. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29855. }
  29856. if (this.tangents) {
  29857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29858. }
  29859. if (this.uvs) {
  29860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29861. }
  29862. if (this.uvs2) {
  29863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29864. }
  29865. if (this.uvs3) {
  29866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29867. }
  29868. if (this.uvs4) {
  29869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29870. }
  29871. if (this.uvs5) {
  29872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29873. }
  29874. if (this.uvs6) {
  29875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29876. }
  29877. if (this.colors) {
  29878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29879. }
  29880. if (this.matricesIndices) {
  29881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29882. }
  29883. if (this.matricesWeights) {
  29884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29885. }
  29886. if (this.matricesIndicesExtra) {
  29887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29888. }
  29889. if (this.matricesWeightsExtra) {
  29890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29891. }
  29892. if (this.indices) {
  29893. meshOrGeometry.setIndices(this.indices, null);
  29894. }
  29895. return this;
  29896. };
  29897. /**
  29898. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29899. * Returns the VertexData.
  29900. */
  29901. VertexData.prototype.transform = function (matrix) {
  29902. var transformed = BABYLON.Vector3.Zero();
  29903. var index;
  29904. if (this.positions) {
  29905. var position = BABYLON.Vector3.Zero();
  29906. for (index = 0; index < this.positions.length; index += 3) {
  29907. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29908. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29909. this.positions[index] = transformed.x;
  29910. this.positions[index + 1] = transformed.y;
  29911. this.positions[index + 2] = transformed.z;
  29912. }
  29913. }
  29914. if (this.normals) {
  29915. var normal = BABYLON.Vector3.Zero();
  29916. for (index = 0; index < this.normals.length; index += 3) {
  29917. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29918. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29919. this.normals[index] = transformed.x;
  29920. this.normals[index + 1] = transformed.y;
  29921. this.normals[index + 2] = transformed.z;
  29922. }
  29923. }
  29924. if (this.tangents) {
  29925. var tangent = BABYLON.Vector4.Zero();
  29926. var tangentTransformed = BABYLON.Vector4.Zero();
  29927. for (index = 0; index < this.tangents.length; index += 4) {
  29928. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29929. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29930. this.tangents[index] = tangentTransformed.x;
  29931. this.tangents[index + 1] = tangentTransformed.y;
  29932. this.tangents[index + 2] = tangentTransformed.z;
  29933. this.tangents[index + 3] = tangentTransformed.w;
  29934. }
  29935. }
  29936. return this;
  29937. };
  29938. /**
  29939. * Merges the passed VertexData into the current one.
  29940. * Returns the modified VertexData.
  29941. */
  29942. VertexData.prototype.merge = function (other, options) {
  29943. options = options || {};
  29944. if (other.indices) {
  29945. if (!this.indices) {
  29946. this.indices = [];
  29947. }
  29948. var offset = this.positions ? this.positions.length / 3 : 0;
  29949. for (var index = 0; index < other.indices.length; index++) {
  29950. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29951. this.indices.push(other.indices[index] + offset);
  29952. }
  29953. }
  29954. this.positions = this._mergeElement(this.positions, other.positions);
  29955. if (!this.positions) {
  29956. return this;
  29957. }
  29958. var count = this.positions.length / 3;
  29959. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29960. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29961. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29962. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29963. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29964. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29965. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29966. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29967. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29968. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29969. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29970. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29971. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29972. return this;
  29973. };
  29974. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29975. if (length === void 0) { length = 0; }
  29976. if (defaultValue === void 0) { defaultValue = 0; }
  29977. if (!other && !source) {
  29978. return null;
  29979. }
  29980. if (!other) {
  29981. var padding = new Float32Array(source.length);
  29982. padding.fill(defaultValue);
  29983. return this._mergeElement(source, padding, length);
  29984. }
  29985. if (!source) {
  29986. if (length === 0 || length === other.length) {
  29987. return other;
  29988. }
  29989. var padding = new Float32Array(length - other.length);
  29990. padding.fill(defaultValue);
  29991. return this._mergeElement(padding, other, length);
  29992. }
  29993. var len = other.length + source.length;
  29994. var isSrcTypedArray = source instanceof Float32Array;
  29995. var isOthTypedArray = other instanceof Float32Array;
  29996. // use non-loop method when the source is Float32Array
  29997. if (isSrcTypedArray) {
  29998. var ret32 = new Float32Array(len);
  29999. ret32.set(source);
  30000. ret32.set(other, source.length);
  30001. return ret32;
  30002. // source is number[], when other is also use concat
  30003. }
  30004. else if (!isOthTypedArray) {
  30005. return source.concat(other);
  30006. // source is a number[], but other is a Float32Array, loop required
  30007. }
  30008. else {
  30009. var ret = source.slice(0); // copy source to a separate array
  30010. for (var i = 0, len = other.length; i < len; i++) {
  30011. ret.push(other[i]);
  30012. }
  30013. return ret;
  30014. }
  30015. };
  30016. /**
  30017. * Serializes the VertexData.
  30018. * Returns a serialized object.
  30019. */
  30020. VertexData.prototype.serialize = function () {
  30021. var serializationObject = this.serialize();
  30022. if (this.positions) {
  30023. serializationObject.positions = this.positions;
  30024. }
  30025. if (this.normals) {
  30026. serializationObject.normals = this.normals;
  30027. }
  30028. if (this.tangents) {
  30029. serializationObject.tangents = this.tangents;
  30030. }
  30031. if (this.uvs) {
  30032. serializationObject.uvs = this.uvs;
  30033. }
  30034. if (this.uvs2) {
  30035. serializationObject.uvs2 = this.uvs2;
  30036. }
  30037. if (this.uvs3) {
  30038. serializationObject.uvs3 = this.uvs3;
  30039. }
  30040. if (this.uvs4) {
  30041. serializationObject.uvs4 = this.uvs4;
  30042. }
  30043. if (this.uvs5) {
  30044. serializationObject.uvs5 = this.uvs5;
  30045. }
  30046. if (this.uvs6) {
  30047. serializationObject.uvs6 = this.uvs6;
  30048. }
  30049. if (this.colors) {
  30050. serializationObject.colors = this.colors;
  30051. }
  30052. if (this.matricesIndices) {
  30053. serializationObject.matricesIndices = this.matricesIndices;
  30054. serializationObject.matricesIndices._isExpanded = true;
  30055. }
  30056. if (this.matricesWeights) {
  30057. serializationObject.matricesWeights = this.matricesWeights;
  30058. }
  30059. if (this.matricesIndicesExtra) {
  30060. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30061. serializationObject.matricesIndicesExtra._isExpanded = true;
  30062. }
  30063. if (this.matricesWeightsExtra) {
  30064. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30065. }
  30066. serializationObject.indices = this.indices;
  30067. return serializationObject;
  30068. };
  30069. // Statics
  30070. /**
  30071. * Returns the object VertexData associated to the passed mesh.
  30072. */
  30073. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30074. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30075. };
  30076. /**
  30077. * Returns the object VertexData associated to the passed geometry.
  30078. */
  30079. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30080. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30081. };
  30082. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30083. var result = new VertexData();
  30084. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30085. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30086. }
  30087. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30088. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30089. }
  30090. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30091. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30092. }
  30093. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30094. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30095. }
  30096. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30097. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30098. }
  30099. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30100. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30101. }
  30102. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30103. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30104. }
  30105. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30106. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30107. }
  30108. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30109. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30110. }
  30111. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30112. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30113. }
  30114. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30115. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30116. }
  30117. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30118. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30119. }
  30120. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30121. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30122. }
  30123. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30124. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30125. }
  30126. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30127. return result;
  30128. };
  30129. /**
  30130. * Creates the vertexData of the Ribbon.
  30131. */
  30132. VertexData.CreateRibbon = function (options) {
  30133. var pathArray = options.pathArray;
  30134. var closeArray = options.closeArray || false;
  30135. var closePath = options.closePath || false;
  30136. var invertUV = options.invertUV || false;
  30137. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30138. var offset = options.offset || defaultOffset;
  30139. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30140. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30141. var customUV = options.uvs;
  30142. var customColors = options.colors;
  30143. var positions = [];
  30144. var indices = [];
  30145. var normals = [];
  30146. var uvs = [];
  30147. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30148. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30149. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30150. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30151. var minlg; // minimal length among all paths from pathArray
  30152. var lg = []; // array of path lengths : nb of vertex per path
  30153. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30154. var p; // path iterator
  30155. var i; // point iterator
  30156. var j; // point iterator
  30157. // if single path in pathArray
  30158. if (pathArray.length < 2) {
  30159. var ar1 = [];
  30160. var ar2 = [];
  30161. for (i = 0; i < pathArray[0].length - offset; i++) {
  30162. ar1.push(pathArray[0][i]);
  30163. ar2.push(pathArray[0][i + offset]);
  30164. }
  30165. pathArray = [ar1, ar2];
  30166. }
  30167. // positions and horizontal distances (u)
  30168. var idc = 0;
  30169. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30170. var path;
  30171. var l;
  30172. minlg = pathArray[0].length;
  30173. var vectlg;
  30174. var dist;
  30175. for (p = 0; p < pathArray.length; p++) {
  30176. uTotalDistance[p] = 0;
  30177. us[p] = [0];
  30178. path = pathArray[p];
  30179. l = path.length;
  30180. minlg = (minlg < l) ? minlg : l;
  30181. j = 0;
  30182. while (j < l) {
  30183. positions.push(path[j].x, path[j].y, path[j].z);
  30184. if (j > 0) {
  30185. vectlg = path[j].subtract(path[j - 1]).length();
  30186. dist = vectlg + uTotalDistance[p];
  30187. us[p].push(dist);
  30188. uTotalDistance[p] = dist;
  30189. }
  30190. j++;
  30191. }
  30192. if (closePath) {
  30193. j--;
  30194. positions.push(path[0].x, path[0].y, path[0].z);
  30195. vectlg = path[j].subtract(path[0]).length();
  30196. dist = vectlg + uTotalDistance[p];
  30197. us[p].push(dist);
  30198. uTotalDistance[p] = dist;
  30199. }
  30200. lg[p] = l + closePathCorr;
  30201. idx[p] = idc;
  30202. idc += (l + closePathCorr);
  30203. }
  30204. // vertical distances (v)
  30205. var path1;
  30206. var path2;
  30207. var vertex1 = null;
  30208. var vertex2 = null;
  30209. for (i = 0; i < minlg + closePathCorr; i++) {
  30210. vTotalDistance[i] = 0;
  30211. vs[i] = [0];
  30212. for (p = 0; p < pathArray.length - 1; p++) {
  30213. path1 = pathArray[p];
  30214. path2 = pathArray[p + 1];
  30215. if (i === minlg) {
  30216. vertex1 = path1[0];
  30217. vertex2 = path2[0];
  30218. }
  30219. else {
  30220. vertex1 = path1[i];
  30221. vertex2 = path2[i];
  30222. }
  30223. vectlg = vertex2.subtract(vertex1).length();
  30224. dist = vectlg + vTotalDistance[i];
  30225. vs[i].push(dist);
  30226. vTotalDistance[i] = dist;
  30227. }
  30228. if (closeArray && vertex2 && vertex1) {
  30229. path1 = pathArray[p];
  30230. path2 = pathArray[0];
  30231. if (i === minlg) {
  30232. vertex2 = path2[0];
  30233. }
  30234. vectlg = vertex2.subtract(vertex1).length();
  30235. dist = vectlg + vTotalDistance[i];
  30236. vTotalDistance[i] = dist;
  30237. }
  30238. }
  30239. // uvs
  30240. var u;
  30241. var v;
  30242. if (customUV) {
  30243. for (p = 0; p < customUV.length; p++) {
  30244. uvs.push(customUV[p].x, customUV[p].y);
  30245. }
  30246. }
  30247. else {
  30248. for (p = 0; p < pathArray.length; p++) {
  30249. for (i = 0; i < minlg + closePathCorr; i++) {
  30250. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30251. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30252. if (invertUV) {
  30253. uvs.push(v, u);
  30254. }
  30255. else {
  30256. uvs.push(u, v);
  30257. }
  30258. }
  30259. }
  30260. }
  30261. // indices
  30262. p = 0; // path index
  30263. var pi = 0; // positions array index
  30264. var l1 = lg[p] - 1; // path1 length
  30265. var l2 = lg[p + 1] - 1; // path2 length
  30266. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30267. var shft = idx[1] - idx[0]; // shift
  30268. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30269. while (pi <= min && p < path1nb) {
  30270. // 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
  30271. indices.push(pi, pi + shft, pi + 1);
  30272. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30273. pi += 1;
  30274. if (pi === min) {
  30275. p++;
  30276. if (p === lg.length - 1) {
  30277. shft = idx[0] - idx[p];
  30278. l1 = lg[p] - 1;
  30279. l2 = lg[0] - 1;
  30280. }
  30281. else {
  30282. shft = idx[p + 1] - idx[p];
  30283. l1 = lg[p] - 1;
  30284. l2 = lg[p + 1] - 1;
  30285. }
  30286. pi = idx[p];
  30287. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30288. }
  30289. }
  30290. // normals
  30291. VertexData.ComputeNormals(positions, indices, normals);
  30292. if (closePath) {
  30293. var indexFirst = 0;
  30294. var indexLast = 0;
  30295. for (p = 0; p < pathArray.length; p++) {
  30296. indexFirst = idx[p] * 3;
  30297. if (p + 1 < pathArray.length) {
  30298. indexLast = (idx[p + 1] - 1) * 3;
  30299. }
  30300. else {
  30301. indexLast = normals.length - 3;
  30302. }
  30303. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30304. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30305. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30306. normals[indexLast] = normals[indexFirst];
  30307. normals[indexLast + 1] = normals[indexFirst + 1];
  30308. normals[indexLast + 2] = normals[indexFirst + 2];
  30309. }
  30310. }
  30311. // sides
  30312. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30313. // Colors
  30314. var colors = null;
  30315. if (customColors) {
  30316. colors = new Float32Array(customColors.length * 4);
  30317. for (var c = 0; c < customColors.length; c++) {
  30318. colors[c * 4] = customColors[c].r;
  30319. colors[c * 4 + 1] = customColors[c].g;
  30320. colors[c * 4 + 2] = customColors[c].b;
  30321. colors[c * 4 + 3] = customColors[c].a;
  30322. }
  30323. }
  30324. // Result
  30325. var vertexData = new VertexData();
  30326. var positions32 = new Float32Array(positions);
  30327. var normals32 = new Float32Array(normals);
  30328. var uvs32 = new Float32Array(uvs);
  30329. vertexData.indices = indices;
  30330. vertexData.positions = positions32;
  30331. vertexData.normals = normals32;
  30332. vertexData.uvs = uvs32;
  30333. if (colors) {
  30334. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30335. }
  30336. if (closePath) {
  30337. vertexData._idx = idx;
  30338. }
  30339. return vertexData;
  30340. };
  30341. /**
  30342. * Creates the VertexData of the Box.
  30343. */
  30344. VertexData.CreateBox = function (options) {
  30345. var normalsSource = [
  30346. new BABYLON.Vector3(0, 0, 1),
  30347. new BABYLON.Vector3(0, 0, -1),
  30348. new BABYLON.Vector3(1, 0, 0),
  30349. new BABYLON.Vector3(-1, 0, 0),
  30350. new BABYLON.Vector3(0, 1, 0),
  30351. new BABYLON.Vector3(0, -1, 0)
  30352. ];
  30353. var indices = [];
  30354. var positions = [];
  30355. var normals = [];
  30356. var uvs = [];
  30357. var width = options.width || options.size || 1;
  30358. var height = options.height || options.size || 1;
  30359. var depth = options.depth || options.size || 1;
  30360. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30361. var faceUV = options.faceUV || new Array(6);
  30362. var faceColors = options.faceColors;
  30363. var colors = [];
  30364. // default face colors and UV if undefined
  30365. for (var f = 0; f < 6; f++) {
  30366. if (faceUV[f] === undefined) {
  30367. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30368. }
  30369. if (faceColors && faceColors[f] === undefined) {
  30370. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30371. }
  30372. }
  30373. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30374. // Create each face in turn.
  30375. for (var index = 0; index < normalsSource.length; index++) {
  30376. var normal = normalsSource[index];
  30377. // Get two vectors perpendicular to the face normal and to each other.
  30378. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30379. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30380. // Six indices (two triangles) per face.
  30381. var verticesLength = positions.length / 3;
  30382. indices.push(verticesLength);
  30383. indices.push(verticesLength + 1);
  30384. indices.push(verticesLength + 2);
  30385. indices.push(verticesLength);
  30386. indices.push(verticesLength + 2);
  30387. indices.push(verticesLength + 3);
  30388. // Four vertices per face.
  30389. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30390. positions.push(vertex.x, vertex.y, vertex.z);
  30391. normals.push(normal.x, normal.y, normal.z);
  30392. uvs.push(faceUV[index].z, faceUV[index].w);
  30393. if (faceColors) {
  30394. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30395. }
  30396. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30397. positions.push(vertex.x, vertex.y, vertex.z);
  30398. normals.push(normal.x, normal.y, normal.z);
  30399. uvs.push(faceUV[index].x, faceUV[index].w);
  30400. if (faceColors) {
  30401. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30402. }
  30403. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30404. positions.push(vertex.x, vertex.y, vertex.z);
  30405. normals.push(normal.x, normal.y, normal.z);
  30406. uvs.push(faceUV[index].x, faceUV[index].y);
  30407. if (faceColors) {
  30408. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30409. }
  30410. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30411. positions.push(vertex.x, vertex.y, vertex.z);
  30412. normals.push(normal.x, normal.y, normal.z);
  30413. uvs.push(faceUV[index].z, faceUV[index].y);
  30414. if (faceColors) {
  30415. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30416. }
  30417. }
  30418. // sides
  30419. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30420. // Result
  30421. var vertexData = new VertexData();
  30422. vertexData.indices = indices;
  30423. vertexData.positions = positions;
  30424. vertexData.normals = normals;
  30425. vertexData.uvs = uvs;
  30426. if (faceColors) {
  30427. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30428. vertexData.colors = totalColors;
  30429. }
  30430. return vertexData;
  30431. };
  30432. /**
  30433. * Creates the VertexData of the Sphere.
  30434. */
  30435. VertexData.CreateSphere = function (options) {
  30436. var segments = options.segments || 32;
  30437. var diameterX = options.diameterX || options.diameter || 1;
  30438. var diameterY = options.diameterY || options.diameter || 1;
  30439. var diameterZ = options.diameterZ || options.diameter || 1;
  30440. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30441. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30442. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30443. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30444. var totalZRotationSteps = 2 + segments;
  30445. var totalYRotationSteps = 2 * totalZRotationSteps;
  30446. var indices = [];
  30447. var positions = [];
  30448. var normals = [];
  30449. var uvs = [];
  30450. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30451. var normalizedZ = zRotationStep / totalZRotationSteps;
  30452. var angleZ = normalizedZ * Math.PI * slice;
  30453. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30454. var normalizedY = yRotationStep / totalYRotationSteps;
  30455. var angleY = normalizedY * Math.PI * 2 * arc;
  30456. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30457. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30458. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30459. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30460. var vertex = complete.multiply(radius);
  30461. var normal = complete.divide(radius).normalize();
  30462. positions.push(vertex.x, vertex.y, vertex.z);
  30463. normals.push(normal.x, normal.y, normal.z);
  30464. uvs.push(normalizedY, normalizedZ);
  30465. }
  30466. if (zRotationStep > 0) {
  30467. var verticesCount = positions.length / 3;
  30468. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30469. indices.push((firstIndex));
  30470. indices.push((firstIndex + 1));
  30471. indices.push(firstIndex + totalYRotationSteps + 1);
  30472. indices.push((firstIndex + totalYRotationSteps + 1));
  30473. indices.push((firstIndex + 1));
  30474. indices.push((firstIndex + totalYRotationSteps + 2));
  30475. }
  30476. }
  30477. }
  30478. // Sides
  30479. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30480. // Result
  30481. var vertexData = new VertexData();
  30482. vertexData.indices = indices;
  30483. vertexData.positions = positions;
  30484. vertexData.normals = normals;
  30485. vertexData.uvs = uvs;
  30486. return vertexData;
  30487. };
  30488. /**
  30489. * Creates the VertexData of the Cylinder or Cone.
  30490. */
  30491. VertexData.CreateCylinder = function (options) {
  30492. var height = options.height || 2;
  30493. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30494. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30495. var tessellation = options.tessellation || 24;
  30496. var subdivisions = options.subdivisions || 1;
  30497. var hasRings = options.hasRings ? true : false;
  30498. var enclose = options.enclose ? true : false;
  30499. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30500. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30501. var faceUV = options.faceUV || new Array(3);
  30502. var faceColors = options.faceColors;
  30503. // default face colors and UV if undefined
  30504. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30505. var ringNb = (hasRings) ? subdivisions : 1;
  30506. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30507. var f;
  30508. for (f = 0; f < surfaceNb; f++) {
  30509. if (faceColors && faceColors[f] === undefined) {
  30510. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30511. }
  30512. }
  30513. for (f = 0; f < surfaceNb; f++) {
  30514. if (faceUV && faceUV[f] === undefined) {
  30515. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30516. }
  30517. }
  30518. var indices = new Array();
  30519. var positions = new Array();
  30520. var normals = new Array();
  30521. var uvs = new Array();
  30522. var colors = new Array();
  30523. var angle_step = Math.PI * 2 * arc / tessellation;
  30524. var angle;
  30525. var h;
  30526. var radius;
  30527. var tan = (diameterBottom - diameterTop) / 2 / height;
  30528. var ringVertex = BABYLON.Vector3.Zero();
  30529. var ringNormal = BABYLON.Vector3.Zero();
  30530. var ringFirstVertex = BABYLON.Vector3.Zero();
  30531. var ringFirstNormal = BABYLON.Vector3.Zero();
  30532. var quadNormal = BABYLON.Vector3.Zero();
  30533. var Y = BABYLON.Axis.Y;
  30534. // positions, normals, uvs
  30535. var i;
  30536. var j;
  30537. var r;
  30538. var ringIdx = 1;
  30539. var s = 1; // surface index
  30540. var cs = 0;
  30541. var v = 0;
  30542. for (i = 0; i <= subdivisions; i++) {
  30543. h = i / subdivisions;
  30544. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30545. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30546. for (r = 0; r < ringIdx; r++) {
  30547. if (hasRings) {
  30548. s += r;
  30549. }
  30550. if (enclose) {
  30551. s += 2 * r;
  30552. }
  30553. for (j = 0; j <= tessellation; j++) {
  30554. angle = j * angle_step;
  30555. // position
  30556. ringVertex.x = Math.cos(-angle) * radius;
  30557. ringVertex.y = -height / 2 + h * height;
  30558. ringVertex.z = Math.sin(-angle) * radius;
  30559. // normal
  30560. if (diameterTop === 0 && i === subdivisions) {
  30561. // if no top cap, reuse former normals
  30562. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30563. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30564. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30565. }
  30566. else {
  30567. ringNormal.x = ringVertex.x;
  30568. ringNormal.z = ringVertex.z;
  30569. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30570. ringNormal.normalize();
  30571. }
  30572. // keep first ring vertex values for enclose
  30573. if (j === 0) {
  30574. ringFirstVertex.copyFrom(ringVertex);
  30575. ringFirstNormal.copyFrom(ringNormal);
  30576. }
  30577. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30578. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30579. if (hasRings) {
  30580. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30581. }
  30582. else {
  30583. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30584. }
  30585. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30586. if (faceColors) {
  30587. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30588. }
  30589. }
  30590. // if enclose, add four vertices and their dedicated normals
  30591. if (arc !== 1 && enclose) {
  30592. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30593. positions.push(0, ringVertex.y, 0);
  30594. positions.push(0, ringVertex.y, 0);
  30595. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30596. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30597. quadNormal.normalize();
  30598. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30599. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30600. quadNormal.normalize();
  30601. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30602. if (hasRings) {
  30603. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30604. }
  30605. else {
  30606. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30607. }
  30608. uvs.push(faceUV[s + 1].x, v);
  30609. uvs.push(faceUV[s + 1].z, v);
  30610. if (hasRings) {
  30611. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30612. }
  30613. else {
  30614. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30615. }
  30616. uvs.push(faceUV[s + 2].x, v);
  30617. uvs.push(faceUV[s + 2].z, v);
  30618. if (faceColors) {
  30619. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30620. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30621. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30622. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30623. }
  30624. }
  30625. if (cs !== s) {
  30626. cs = s;
  30627. }
  30628. }
  30629. }
  30630. // indices
  30631. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30632. var s;
  30633. i = 0;
  30634. for (s = 0; s < subdivisions; s++) {
  30635. var i0 = 0;
  30636. var i1 = 0;
  30637. var i2 = 0;
  30638. var i3 = 0;
  30639. for (j = 0; j < tessellation; j++) {
  30640. i0 = i * (e + 1) + j;
  30641. i1 = (i + 1) * (e + 1) + j;
  30642. i2 = i * (e + 1) + (j + 1);
  30643. i3 = (i + 1) * (e + 1) + (j + 1);
  30644. indices.push(i0, i1, i2);
  30645. indices.push(i3, i2, i1);
  30646. }
  30647. if (arc !== 1 && enclose) {
  30648. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30649. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30650. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30651. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30652. }
  30653. i = (hasRings) ? (i + 2) : (i + 1);
  30654. }
  30655. // Caps
  30656. var createCylinderCap = function (isTop) {
  30657. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30658. if (radius === 0) {
  30659. return;
  30660. }
  30661. // Cap positions, normals & uvs
  30662. var angle;
  30663. var circleVector;
  30664. var i;
  30665. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30666. var c = null;
  30667. if (faceColors) {
  30668. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30669. }
  30670. // cap center
  30671. var vbase = positions.length / 3;
  30672. var offset = isTop ? height / 2 : -height / 2;
  30673. var center = new BABYLON.Vector3(0, offset, 0);
  30674. positions.push(center.x, center.y, center.z);
  30675. normals.push(0, isTop ? 1 : -1, 0);
  30676. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30677. if (c) {
  30678. colors.push(c.r, c.g, c.b, c.a);
  30679. }
  30680. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30681. for (i = 0; i <= tessellation; i++) {
  30682. angle = Math.PI * 2 * i * arc / tessellation;
  30683. var cos = Math.cos(-angle);
  30684. var sin = Math.sin(-angle);
  30685. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30686. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30687. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30688. normals.push(0, isTop ? 1 : -1, 0);
  30689. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30690. if (c) {
  30691. colors.push(c.r, c.g, c.b, c.a);
  30692. }
  30693. }
  30694. // Cap indices
  30695. for (i = 0; i < tessellation; i++) {
  30696. if (!isTop) {
  30697. indices.push(vbase);
  30698. indices.push(vbase + (i + 1));
  30699. indices.push(vbase + (i + 2));
  30700. }
  30701. else {
  30702. indices.push(vbase);
  30703. indices.push(vbase + (i + 2));
  30704. indices.push(vbase + (i + 1));
  30705. }
  30706. }
  30707. };
  30708. // add caps to geometry
  30709. createCylinderCap(false);
  30710. createCylinderCap(true);
  30711. // Sides
  30712. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30713. var vertexData = new VertexData();
  30714. vertexData.indices = indices;
  30715. vertexData.positions = positions;
  30716. vertexData.normals = normals;
  30717. vertexData.uvs = uvs;
  30718. if (faceColors) {
  30719. vertexData.colors = colors;
  30720. }
  30721. return vertexData;
  30722. };
  30723. /**
  30724. * Creates the VertexData of the Torus.
  30725. */
  30726. VertexData.CreateTorus = function (options) {
  30727. var indices = [];
  30728. var positions = [];
  30729. var normals = [];
  30730. var uvs = [];
  30731. var diameter = options.diameter || 1;
  30732. var thickness = options.thickness || 0.5;
  30733. var tessellation = options.tessellation || 16;
  30734. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30735. var stride = tessellation + 1;
  30736. for (var i = 0; i <= tessellation; i++) {
  30737. var u = i / tessellation;
  30738. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30739. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30740. for (var j = 0; j <= tessellation; j++) {
  30741. var v = 1 - j / tessellation;
  30742. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30743. var dx = Math.cos(innerAngle);
  30744. var dy = Math.sin(innerAngle);
  30745. // Create a vertex.
  30746. var normal = new BABYLON.Vector3(dx, dy, 0);
  30747. var position = normal.scale(thickness / 2);
  30748. var textureCoordinate = new BABYLON.Vector2(u, v);
  30749. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30750. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30751. positions.push(position.x, position.y, position.z);
  30752. normals.push(normal.x, normal.y, normal.z);
  30753. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30754. // And create indices for two triangles.
  30755. var nextI = (i + 1) % stride;
  30756. var nextJ = (j + 1) % stride;
  30757. indices.push(i * stride + j);
  30758. indices.push(i * stride + nextJ);
  30759. indices.push(nextI * stride + j);
  30760. indices.push(i * stride + nextJ);
  30761. indices.push(nextI * stride + nextJ);
  30762. indices.push(nextI * stride + j);
  30763. }
  30764. }
  30765. // Sides
  30766. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30767. // Result
  30768. var vertexData = new VertexData();
  30769. vertexData.indices = indices;
  30770. vertexData.positions = positions;
  30771. vertexData.normals = normals;
  30772. vertexData.uvs = uvs;
  30773. return vertexData;
  30774. };
  30775. /**
  30776. * Creates the VertexData of the LineSystem.
  30777. */
  30778. VertexData.CreateLineSystem = function (options) {
  30779. var indices = [];
  30780. var positions = [];
  30781. var lines = options.lines;
  30782. var colors = options.colors;
  30783. var vertexColors = [];
  30784. var idx = 0;
  30785. for (var l = 0; l < lines.length; l++) {
  30786. var points = lines[l];
  30787. for (var index = 0; index < points.length; index++) {
  30788. positions.push(points[index].x, points[index].y, points[index].z);
  30789. if (colors) {
  30790. var color = colors[l];
  30791. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30792. }
  30793. if (index > 0) {
  30794. indices.push(idx - 1);
  30795. indices.push(idx);
  30796. }
  30797. idx++;
  30798. }
  30799. }
  30800. var vertexData = new VertexData();
  30801. vertexData.indices = indices;
  30802. vertexData.positions = positions;
  30803. if (colors) {
  30804. vertexData.colors = vertexColors;
  30805. }
  30806. return vertexData;
  30807. };
  30808. /**
  30809. * Create the VertexData of the DashedLines.
  30810. */
  30811. VertexData.CreateDashedLines = function (options) {
  30812. var dashSize = options.dashSize || 3;
  30813. var gapSize = options.gapSize || 1;
  30814. var dashNb = options.dashNb || 200;
  30815. var points = options.points;
  30816. var positions = new Array();
  30817. var indices = new Array();
  30818. var curvect = BABYLON.Vector3.Zero();
  30819. var lg = 0;
  30820. var nb = 0;
  30821. var shft = 0;
  30822. var dashshft = 0;
  30823. var curshft = 0;
  30824. var idx = 0;
  30825. var i = 0;
  30826. for (i = 0; i < points.length - 1; i++) {
  30827. points[i + 1].subtractToRef(points[i], curvect);
  30828. lg += curvect.length();
  30829. }
  30830. shft = lg / dashNb;
  30831. dashshft = dashSize * shft / (dashSize + gapSize);
  30832. for (i = 0; i < points.length - 1; i++) {
  30833. points[i + 1].subtractToRef(points[i], curvect);
  30834. nb = Math.floor(curvect.length() / shft);
  30835. curvect.normalize();
  30836. for (var j = 0; j < nb; j++) {
  30837. curshft = shft * j;
  30838. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30839. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30840. indices.push(idx, idx + 1);
  30841. idx += 2;
  30842. }
  30843. }
  30844. // Result
  30845. var vertexData = new VertexData();
  30846. vertexData.positions = positions;
  30847. vertexData.indices = indices;
  30848. return vertexData;
  30849. };
  30850. /**
  30851. * Creates the VertexData of the Ground.
  30852. */
  30853. VertexData.CreateGround = function (options) {
  30854. var indices = [];
  30855. var positions = [];
  30856. var normals = [];
  30857. var uvs = [];
  30858. var row, col;
  30859. var width = options.width || 1;
  30860. var height = options.height || 1;
  30861. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30862. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30863. for (row = 0; row <= subdivisionsY; row++) {
  30864. for (col = 0; col <= subdivisionsX; col++) {
  30865. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30866. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30867. positions.push(position.x, position.y, position.z);
  30868. normals.push(normal.x, normal.y, normal.z);
  30869. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30870. }
  30871. }
  30872. for (row = 0; row < subdivisionsY; row++) {
  30873. for (col = 0; col < subdivisionsX; col++) {
  30874. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30875. indices.push(col + 1 + row * (subdivisionsX + 1));
  30876. indices.push(col + row * (subdivisionsX + 1));
  30877. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30878. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30879. indices.push(col + row * (subdivisionsX + 1));
  30880. }
  30881. }
  30882. // Result
  30883. var vertexData = new VertexData();
  30884. vertexData.indices = indices;
  30885. vertexData.positions = positions;
  30886. vertexData.normals = normals;
  30887. vertexData.uvs = uvs;
  30888. return vertexData;
  30889. };
  30890. /**
  30891. * Creates the VertexData of the TiledGround.
  30892. */
  30893. VertexData.CreateTiledGround = function (options) {
  30894. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30895. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30896. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30897. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30898. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30899. var precision = options.precision || { w: 1, h: 1 };
  30900. var indices = new Array();
  30901. var positions = new Array();
  30902. var normals = new Array();
  30903. var uvs = new Array();
  30904. var row, col, tileRow, tileCol;
  30905. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30906. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30907. precision.w = (precision.w < 1) ? 1 : precision.w;
  30908. precision.h = (precision.h < 1) ? 1 : precision.h;
  30909. var tileSize = {
  30910. 'w': (xmax - xmin) / subdivisions.w,
  30911. 'h': (zmax - zmin) / subdivisions.h
  30912. };
  30913. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30914. // Indices
  30915. var base = positions.length / 3;
  30916. var rowLength = precision.w + 1;
  30917. for (row = 0; row < precision.h; row++) {
  30918. for (col = 0; col < precision.w; col++) {
  30919. var square = [
  30920. base + col + row * rowLength,
  30921. base + (col + 1) + row * rowLength,
  30922. base + (col + 1) + (row + 1) * rowLength,
  30923. base + col + (row + 1) * rowLength
  30924. ];
  30925. indices.push(square[1]);
  30926. indices.push(square[2]);
  30927. indices.push(square[3]);
  30928. indices.push(square[0]);
  30929. indices.push(square[1]);
  30930. indices.push(square[3]);
  30931. }
  30932. }
  30933. // Position, normals and uvs
  30934. var position = BABYLON.Vector3.Zero();
  30935. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30936. for (row = 0; row <= precision.h; row++) {
  30937. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30938. for (col = 0; col <= precision.w; col++) {
  30939. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30940. position.y = 0;
  30941. positions.push(position.x, position.y, position.z);
  30942. normals.push(normal.x, normal.y, normal.z);
  30943. uvs.push(col / precision.w, row / precision.h);
  30944. }
  30945. }
  30946. }
  30947. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30948. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30949. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30950. }
  30951. }
  30952. // Result
  30953. var vertexData = new VertexData();
  30954. vertexData.indices = indices;
  30955. vertexData.positions = positions;
  30956. vertexData.normals = normals;
  30957. vertexData.uvs = uvs;
  30958. return vertexData;
  30959. };
  30960. /**
  30961. * Creates the VertexData of the Ground designed from a heightmap.
  30962. */
  30963. VertexData.CreateGroundFromHeightMap = function (options) {
  30964. var indices = [];
  30965. var positions = [];
  30966. var normals = [];
  30967. var uvs = [];
  30968. var row, col;
  30969. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30970. // Vertices
  30971. for (row = 0; row <= options.subdivisions; row++) {
  30972. for (col = 0; col <= options.subdivisions; col++) {
  30973. 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));
  30974. // Compute height
  30975. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30976. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30977. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30978. var r = options.buffer[pos] / 255.0;
  30979. var g = options.buffer[pos + 1] / 255.0;
  30980. var b = options.buffer[pos + 2] / 255.0;
  30981. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30982. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30983. // Add vertex
  30984. positions.push(position.x, position.y, position.z);
  30985. normals.push(0, 0, 0);
  30986. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30987. }
  30988. }
  30989. // Indices
  30990. for (row = 0; row < options.subdivisions; row++) {
  30991. for (col = 0; col < options.subdivisions; col++) {
  30992. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30993. indices.push(col + 1 + row * (options.subdivisions + 1));
  30994. indices.push(col + row * (options.subdivisions + 1));
  30995. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30996. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30997. indices.push(col + row * (options.subdivisions + 1));
  30998. }
  30999. }
  31000. // Normals
  31001. VertexData.ComputeNormals(positions, indices, normals);
  31002. // Result
  31003. var vertexData = new VertexData();
  31004. vertexData.indices = indices;
  31005. vertexData.positions = positions;
  31006. vertexData.normals = normals;
  31007. vertexData.uvs = uvs;
  31008. return vertexData;
  31009. };
  31010. /**
  31011. * Creates the VertexData of the Plane.
  31012. */
  31013. VertexData.CreatePlane = function (options) {
  31014. var indices = [];
  31015. var positions = [];
  31016. var normals = [];
  31017. var uvs = [];
  31018. var width = options.width || options.size || 1;
  31019. var height = options.height || options.size || 1;
  31020. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31021. // Vertices
  31022. var halfWidth = width / 2.0;
  31023. var halfHeight = height / 2.0;
  31024. positions.push(-halfWidth, -halfHeight, 0);
  31025. normals.push(0, 0, -1.0);
  31026. uvs.push(0.0, 0.0);
  31027. positions.push(halfWidth, -halfHeight, 0);
  31028. normals.push(0, 0, -1.0);
  31029. uvs.push(1.0, 0.0);
  31030. positions.push(halfWidth, halfHeight, 0);
  31031. normals.push(0, 0, -1.0);
  31032. uvs.push(1.0, 1.0);
  31033. positions.push(-halfWidth, halfHeight, 0);
  31034. normals.push(0, 0, -1.0);
  31035. uvs.push(0.0, 1.0);
  31036. // Indices
  31037. indices.push(0);
  31038. indices.push(1);
  31039. indices.push(2);
  31040. indices.push(0);
  31041. indices.push(2);
  31042. indices.push(3);
  31043. // Sides
  31044. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31045. // Result
  31046. var vertexData = new VertexData();
  31047. vertexData.indices = indices;
  31048. vertexData.positions = positions;
  31049. vertexData.normals = normals;
  31050. vertexData.uvs = uvs;
  31051. return vertexData;
  31052. };
  31053. /**
  31054. * Creates the VertexData of the Disc or regular Polygon.
  31055. */
  31056. VertexData.CreateDisc = function (options) {
  31057. var positions = new Array();
  31058. var indices = new Array();
  31059. var normals = new Array();
  31060. var uvs = new Array();
  31061. var radius = options.radius || 0.5;
  31062. var tessellation = options.tessellation || 64;
  31063. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31064. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31065. // positions and uvs
  31066. positions.push(0, 0, 0); // disc center first
  31067. uvs.push(0.5, 0.5);
  31068. var theta = Math.PI * 2 * arc;
  31069. var step = theta / tessellation;
  31070. for (var a = 0; a < theta; a += step) {
  31071. var x = Math.cos(a);
  31072. var y = Math.sin(a);
  31073. var u = (x + 1) / 2;
  31074. var v = (1 - y) / 2;
  31075. positions.push(radius * x, radius * y, 0);
  31076. uvs.push(u, v);
  31077. }
  31078. if (arc === 1) {
  31079. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31080. uvs.push(uvs[2], uvs[3]);
  31081. }
  31082. //indices
  31083. var vertexNb = positions.length / 3;
  31084. for (var i = 1; i < vertexNb - 1; i++) {
  31085. indices.push(i + 1, 0, i);
  31086. }
  31087. // result
  31088. VertexData.ComputeNormals(positions, indices, normals);
  31089. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31090. var vertexData = new VertexData();
  31091. vertexData.indices = indices;
  31092. vertexData.positions = positions;
  31093. vertexData.normals = normals;
  31094. vertexData.uvs = uvs;
  31095. return vertexData;
  31096. };
  31097. /**
  31098. * Re-creates the VertexData of the Polygon for sideOrientation.
  31099. */
  31100. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31101. var faceUV = fUV || new Array(3);
  31102. var faceColors = fColors;
  31103. var colors = [];
  31104. // default face colors and UV if undefined
  31105. for (var f = 0; f < 3; f++) {
  31106. if (faceUV[f] === undefined) {
  31107. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31108. }
  31109. if (faceColors && faceColors[f] === undefined) {
  31110. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31111. }
  31112. }
  31113. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31114. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31115. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31116. var indices = polygon.getIndices();
  31117. // set face colours and textures
  31118. var idx = 0;
  31119. var face = 0;
  31120. for (var index = 0; index < normals.length; index += 3) {
  31121. //Edge Face no. 1
  31122. if (Math.abs(normals[index + 1]) < 0.001) {
  31123. face = 1;
  31124. }
  31125. //Top Face no. 0
  31126. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31127. face = 0;
  31128. }
  31129. //Bottom Face no. 2
  31130. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31131. face = 2;
  31132. }
  31133. idx = index / 3;
  31134. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31135. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31136. if (faceColors) {
  31137. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31138. }
  31139. }
  31140. // sides
  31141. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31142. // Result
  31143. var vertexData = new VertexData();
  31144. vertexData.indices = indices;
  31145. vertexData.positions = positions;
  31146. vertexData.normals = normals;
  31147. vertexData.uvs = uvs;
  31148. if (faceColors) {
  31149. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31150. vertexData.colors = totalColors;
  31151. }
  31152. return vertexData;
  31153. };
  31154. /**
  31155. * Creates the VertexData of the IcoSphere.
  31156. */
  31157. VertexData.CreateIcoSphere = function (options) {
  31158. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31159. var radius = options.radius || 1;
  31160. var flat = (options.flat === undefined) ? true : options.flat;
  31161. var subdivisions = options.subdivisions || 4;
  31162. var radiusX = options.radiusX || radius;
  31163. var radiusY = options.radiusY || radius;
  31164. var radiusZ = options.radiusZ || radius;
  31165. var t = (1 + Math.sqrt(5)) / 2;
  31166. // 12 vertex x,y,z
  31167. var ico_vertices = [
  31168. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31169. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31170. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31171. ];
  31172. // index of 3 vertex makes a face of icopshere
  31173. var ico_indices = [
  31174. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31175. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31176. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31177. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31178. ];
  31179. // vertex for uv have aliased position, not for UV
  31180. var vertices_unalias_id = [
  31181. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31182. // vertex alias
  31183. 0,
  31184. 2,
  31185. 3,
  31186. 3,
  31187. 3,
  31188. 4,
  31189. 7,
  31190. 8,
  31191. 9,
  31192. 9,
  31193. 10,
  31194. 11 // 23: B + 12
  31195. ];
  31196. // uv as integer step (not pixels !)
  31197. var ico_vertexuv = [
  31198. 5, 1, 3, 1, 6, 4, 0, 0,
  31199. 5, 3, 4, 2, 2, 2, 4, 0,
  31200. 2, 0, 1, 1, 6, 0, 6, 2,
  31201. // vertex alias (for same vertex on different faces)
  31202. 0, 4,
  31203. 3, 3,
  31204. 4, 4,
  31205. 3, 1,
  31206. 4, 2,
  31207. 4, 4,
  31208. 0, 2,
  31209. 1, 1,
  31210. 2, 2,
  31211. 3, 3,
  31212. 1, 3,
  31213. 2, 4 // 23: B + 12
  31214. ];
  31215. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31216. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31217. // First island of uv mapping
  31218. // v = 4h 3+ 2
  31219. // v = 3h 9+ 4
  31220. // v = 2h 9+ 5 B
  31221. // v = 1h 9 1 0
  31222. // v = 0h 3 8 7 A
  31223. // u = 0 1 2 3 4 5 6 *a
  31224. // Second island of uv mapping
  31225. // v = 4h 0+ B+ 4+
  31226. // v = 3h A+ 2+
  31227. // v = 2h 7+ 6 3+
  31228. // v = 1h 8+ 3+
  31229. // v = 0h
  31230. // u = 0 1 2 3 4 5 6 *a
  31231. // Face layout on texture UV mapping
  31232. // ============
  31233. // \ 4 /\ 16 / ======
  31234. // \ / \ / /\ 11 /
  31235. // \/ 7 \/ / \ /
  31236. // ======= / 10 \/
  31237. // /\ 17 /\ =======
  31238. // / \ / \ \ 15 /\
  31239. // / 8 \/ 12 \ \ / \
  31240. // ============ \/ 6 \
  31241. // \ 18 /\ ============
  31242. // \ / \ \ 5 /\ 0 /
  31243. // \/ 13 \ \ / \ /
  31244. // ======= \/ 1 \/
  31245. // =============
  31246. // /\ 19 /\ 2 /\
  31247. // / \ / \ / \
  31248. // / 14 \/ 9 \/ 3 \
  31249. // ===================
  31250. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31251. var ustep = 138 / 1024;
  31252. var vstep = 239 / 1024;
  31253. var uoffset = 60 / 1024;
  31254. var voffset = 26 / 1024;
  31255. // Second island should have margin, not to touch the first island
  31256. // avoid any borderline artefact in pixel rounding
  31257. var island_u_offset = -40 / 1024;
  31258. var island_v_offset = +20 / 1024;
  31259. // face is either island 0 or 1 :
  31260. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31261. var island = [
  31262. 0, 0, 0, 0, 1,
  31263. 0, 0, 1, 1, 0,
  31264. 0, 0, 1, 1, 0,
  31265. 0, 1, 1, 1, 0 // 15 - 19
  31266. ];
  31267. var indices = new Array();
  31268. var positions = new Array();
  31269. var normals = new Array();
  31270. var uvs = new Array();
  31271. var current_indice = 0;
  31272. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31273. var face_vertex_pos = new Array(3);
  31274. var face_vertex_uv = new Array(3);
  31275. var v012;
  31276. for (v012 = 0; v012 < 3; v012++) {
  31277. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31278. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31279. }
  31280. // create all with normals
  31281. for (var face = 0; face < 20; face++) {
  31282. // 3 vertex per face
  31283. for (v012 = 0; v012 < 3; v012++) {
  31284. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31285. var v_id = ico_indices[3 * face + v012];
  31286. // vertex have 3D position (x,y,z)
  31287. 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]);
  31288. // Normalize to get normal, then scale to radius
  31289. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31290. // uv Coordinates from vertex ID
  31291. 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);
  31292. }
  31293. // Subdivide the face (interpolate pos, norm, uv)
  31294. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31295. // - norm is linear interpolation of vertex corner normal
  31296. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31297. // - uv is linear interpolation
  31298. //
  31299. // Topology is as below for sub-divide by 2
  31300. // vertex shown as v0,v1,v2
  31301. // interp index is i1 to progress in range [v0,v1[
  31302. // interp index is i2 to progress in range [v0,v2[
  31303. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31304. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31305. //
  31306. //
  31307. // i2 v2
  31308. // ^ ^
  31309. // / / \
  31310. // / / \
  31311. // / / \
  31312. // / / (0,1) \
  31313. // / #---------\
  31314. // / / \ (0,0)'/ \
  31315. // / / \ / \
  31316. // / / \ / \
  31317. // / / (0,0) \ / (1,0) \
  31318. // / #---------#---------\
  31319. // v0 v1
  31320. //
  31321. // --------------------> i1
  31322. //
  31323. // interp of (i1,i2):
  31324. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31325. // along i1 : lerp(x0,x1, i1/(S-i2))
  31326. //
  31327. // centroid of triangle is needed to get help normal computation
  31328. // (c1,c2) are used for centroid location
  31329. var interp_vertex = function (i1, i2, c1, c2) {
  31330. // vertex is interpolated from
  31331. // - face_vertex_pos[0..2]
  31332. // - face_vertex_uv[0..2]
  31333. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31334. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31335. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31336. pos_interp.normalize();
  31337. var vertex_normal;
  31338. if (flat) {
  31339. // in flat mode, recalculate normal as face centroid normal
  31340. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31341. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31342. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31343. }
  31344. else {
  31345. // in smooth mode, recalculate normal from each single vertex position
  31346. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31347. }
  31348. // Vertex normal need correction due to X,Y,Z radius scaling
  31349. vertex_normal.x /= radiusX;
  31350. vertex_normal.y /= radiusY;
  31351. vertex_normal.z /= radiusZ;
  31352. vertex_normal.normalize();
  31353. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31354. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31355. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31356. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31357. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31358. uvs.push(uv_interp.x, uv_interp.y);
  31359. // push each vertex has member of a face
  31360. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31361. indices.push(current_indice);
  31362. current_indice++;
  31363. };
  31364. for (var i2 = 0; i2 < subdivisions; i2++) {
  31365. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31366. // face : (i1,i2) for /\ :
  31367. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31368. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31369. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31370. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31371. if (i1 + i2 + 1 < subdivisions) {
  31372. // face : (i1,i2)' for \/ :
  31373. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31374. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31375. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31376. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31377. }
  31378. }
  31379. }
  31380. }
  31381. // Sides
  31382. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31383. // Result
  31384. var vertexData = new VertexData();
  31385. vertexData.indices = indices;
  31386. vertexData.positions = positions;
  31387. vertexData.normals = normals;
  31388. vertexData.uvs = uvs;
  31389. return vertexData;
  31390. };
  31391. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31392. /**
  31393. * Creates the VertexData of the Polyhedron.
  31394. */
  31395. VertexData.CreatePolyhedron = function (options) {
  31396. // provided polyhedron types :
  31397. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31398. // 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)
  31399. var polyhedra = [];
  31400. 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]] };
  31401. 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]] };
  31402. polyhedra[2] = {
  31403. 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]],
  31404. 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]]
  31405. };
  31406. polyhedra[3] = {
  31407. 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]],
  31408. 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]]
  31409. };
  31410. polyhedra[4] = {
  31411. 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]],
  31412. 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]]
  31413. };
  31414. 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]] };
  31415. 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]] };
  31416. 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]] };
  31417. 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]] };
  31418. 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]] };
  31419. 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]] };
  31420. 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]] };
  31421. 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]] };
  31422. 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]] };
  31423. polyhedra[14] = {
  31424. 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]],
  31425. 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]]
  31426. };
  31427. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31428. var size = options.size;
  31429. var sizeX = options.sizeX || size || 1;
  31430. var sizeY = options.sizeY || size || 1;
  31431. var sizeZ = options.sizeZ || size || 1;
  31432. var data = options.custom || polyhedra[type];
  31433. var nbfaces = data.face.length;
  31434. var faceUV = options.faceUV || new Array(nbfaces);
  31435. var faceColors = options.faceColors;
  31436. var flat = (options.flat === undefined) ? true : options.flat;
  31437. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31438. var positions = new Array();
  31439. var indices = new Array();
  31440. var normals = new Array();
  31441. var uvs = new Array();
  31442. var colors = new Array();
  31443. var index = 0;
  31444. var faceIdx = 0; // face cursor in the array "indexes"
  31445. var indexes = new Array();
  31446. var i = 0;
  31447. var f = 0;
  31448. var u, v, ang, x, y, tmp;
  31449. // default face colors and UV if undefined
  31450. if (flat) {
  31451. for (f = 0; f < nbfaces; f++) {
  31452. if (faceColors && faceColors[f] === undefined) {
  31453. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31454. }
  31455. if (faceUV && faceUV[f] === undefined) {
  31456. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31457. }
  31458. }
  31459. }
  31460. if (!flat) {
  31461. for (i = 0; i < data.vertex.length; i++) {
  31462. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31463. uvs.push(0, 0);
  31464. }
  31465. for (f = 0; f < nbfaces; f++) {
  31466. for (i = 0; i < data.face[f].length - 2; i++) {
  31467. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31468. }
  31469. }
  31470. }
  31471. else {
  31472. for (f = 0; f < nbfaces; f++) {
  31473. var fl = data.face[f].length; // number of vertices of the current face
  31474. ang = 2 * Math.PI / fl;
  31475. x = 0.5 * Math.tan(ang / 2);
  31476. y = 0.5;
  31477. // positions, uvs, colors
  31478. for (i = 0; i < fl; i++) {
  31479. // positions
  31480. 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);
  31481. indexes.push(index);
  31482. index++;
  31483. // uvs
  31484. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31485. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31486. uvs.push(u, v);
  31487. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31488. y = x * Math.sin(ang) + y * Math.cos(ang);
  31489. x = tmp;
  31490. // colors
  31491. if (faceColors) {
  31492. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31493. }
  31494. }
  31495. // indices from indexes
  31496. for (i = 0; i < fl - 2; i++) {
  31497. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31498. }
  31499. faceIdx += fl;
  31500. }
  31501. }
  31502. VertexData.ComputeNormals(positions, indices, normals);
  31503. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31504. var vertexData = new VertexData();
  31505. vertexData.positions = positions;
  31506. vertexData.indices = indices;
  31507. vertexData.normals = normals;
  31508. vertexData.uvs = uvs;
  31509. if (faceColors && flat) {
  31510. vertexData.colors = colors;
  31511. }
  31512. return vertexData;
  31513. };
  31514. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31515. /**
  31516. * Creates the VertexData of the Torus Knot.
  31517. */
  31518. VertexData.CreateTorusKnot = function (options) {
  31519. var indices = new Array();
  31520. var positions = new Array();
  31521. var normals = new Array();
  31522. var uvs = new Array();
  31523. var radius = options.radius || 2;
  31524. var tube = options.tube || 0.5;
  31525. var radialSegments = options.radialSegments || 32;
  31526. var tubularSegments = options.tubularSegments || 32;
  31527. var p = options.p || 2;
  31528. var q = options.q || 3;
  31529. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31530. // Helper
  31531. var getPos = function (angle) {
  31532. var cu = Math.cos(angle);
  31533. var su = Math.sin(angle);
  31534. var quOverP = q / p * angle;
  31535. var cs = Math.cos(quOverP);
  31536. var tx = radius * (2 + cs) * 0.5 * cu;
  31537. var ty = radius * (2 + cs) * su * 0.5;
  31538. var tz = radius * Math.sin(quOverP) * 0.5;
  31539. return new BABYLON.Vector3(tx, ty, tz);
  31540. };
  31541. // Vertices
  31542. var i;
  31543. var j;
  31544. for (i = 0; i <= radialSegments; i++) {
  31545. var modI = i % radialSegments;
  31546. var u = modI / radialSegments * 2 * p * Math.PI;
  31547. var p1 = getPos(u);
  31548. var p2 = getPos(u + 0.01);
  31549. var tang = p2.subtract(p1);
  31550. var n = p2.add(p1);
  31551. var bitan = BABYLON.Vector3.Cross(tang, n);
  31552. n = BABYLON.Vector3.Cross(bitan, tang);
  31553. bitan.normalize();
  31554. n.normalize();
  31555. for (j = 0; j < tubularSegments; j++) {
  31556. var modJ = j % tubularSegments;
  31557. var v = modJ / tubularSegments * 2 * Math.PI;
  31558. var cx = -tube * Math.cos(v);
  31559. var cy = tube * Math.sin(v);
  31560. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31561. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31562. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31563. uvs.push(i / radialSegments);
  31564. uvs.push(j / tubularSegments);
  31565. }
  31566. }
  31567. for (i = 0; i < radialSegments; i++) {
  31568. for (j = 0; j < tubularSegments; j++) {
  31569. var jNext = (j + 1) % tubularSegments;
  31570. var a = i * tubularSegments + j;
  31571. var b = (i + 1) * tubularSegments + j;
  31572. var c = (i + 1) * tubularSegments + jNext;
  31573. var d = i * tubularSegments + jNext;
  31574. indices.push(d);
  31575. indices.push(b);
  31576. indices.push(a);
  31577. indices.push(d);
  31578. indices.push(c);
  31579. indices.push(b);
  31580. }
  31581. }
  31582. // Normals
  31583. VertexData.ComputeNormals(positions, indices, normals);
  31584. // Sides
  31585. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31586. // Result
  31587. var vertexData = new VertexData();
  31588. vertexData.indices = indices;
  31589. vertexData.positions = positions;
  31590. vertexData.normals = normals;
  31591. vertexData.uvs = uvs;
  31592. return vertexData;
  31593. };
  31594. // Tools
  31595. /**
  31596. * @param {any} - positions (number[] or Float32Array)
  31597. * @param {any} - indices (number[] or Uint16Array)
  31598. * @param {any} - normals (number[] or Float32Array)
  31599. * options (optional) :
  31600. * facetPositions : optional array of facet positions (vector3)
  31601. * facetNormals : optional array of facet normals (vector3)
  31602. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31603. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31604. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31605. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31606. * bInfo : optional bounding info, required for facetPartitioning computation
  31607. * useRightHandedSystem: optional boolean to for right handed system computation
  31608. * depthSort : optional boolean to enable the facet depth sort computation
  31609. * distanceTo : optional Vector3 to compute the facet depth from this location
  31610. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31611. */
  31612. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31613. // temporary scalar variables
  31614. var index = 0; // facet index
  31615. var p1p2x = 0.0; // p1p2 vector x coordinate
  31616. var p1p2y = 0.0; // p1p2 vector y coordinate
  31617. var p1p2z = 0.0; // p1p2 vector z coordinate
  31618. var p3p2x = 0.0; // p3p2 vector x coordinate
  31619. var p3p2y = 0.0; // p3p2 vector y coordinate
  31620. var p3p2z = 0.0; // p3p2 vector z coordinate
  31621. var faceNormalx = 0.0; // facet normal x coordinate
  31622. var faceNormaly = 0.0; // facet normal y coordinate
  31623. var faceNormalz = 0.0; // facet normal z coordinate
  31624. var length = 0.0; // facet normal length before normalization
  31625. var v1x = 0; // vector1 x index in the positions array
  31626. var v1y = 0; // vector1 y index in the positions array
  31627. var v1z = 0; // vector1 z index in the positions array
  31628. var v2x = 0; // vector2 x index in the positions array
  31629. var v2y = 0; // vector2 y index in the positions array
  31630. var v2z = 0; // vector2 z index in the positions array
  31631. var v3x = 0; // vector3 x index in the positions array
  31632. var v3y = 0; // vector3 y index in the positions array
  31633. var v3z = 0; // vector3 z index in the positions array
  31634. var computeFacetNormals = false;
  31635. var computeFacetPositions = false;
  31636. var computeFacetPartitioning = false;
  31637. var computeDepthSort = false;
  31638. var faceNormalSign = 1;
  31639. var ratio = 0;
  31640. var distanceTo = null;
  31641. if (options) {
  31642. computeFacetNormals = (options.facetNormals) ? true : false;
  31643. computeFacetPositions = (options.facetPositions) ? true : false;
  31644. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31645. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31646. ratio = options.ratio || 0;
  31647. computeDepthSort = (options.depthSort) ? true : false;
  31648. distanceTo = (options.distanceTo);
  31649. if (computeDepthSort) {
  31650. if (distanceTo === undefined) {
  31651. distanceTo = BABYLON.Vector3.Zero();
  31652. }
  31653. var depthSortedFacets = options.depthSortedFacets;
  31654. }
  31655. }
  31656. // facetPartitioning reinit if needed
  31657. var xSubRatio = 0;
  31658. var ySubRatio = 0;
  31659. var zSubRatio = 0;
  31660. var subSq = 0;
  31661. if (computeFacetPartitioning && options && options.bbSize) {
  31662. var ox = 0; // X partitioning index for facet position
  31663. var oy = 0; // Y partinioning index for facet position
  31664. var oz = 0; // Z partinioning index for facet position
  31665. var b1x = 0; // X partitioning index for facet v1 vertex
  31666. var b1y = 0; // Y partitioning index for facet v1 vertex
  31667. var b1z = 0; // z partitioning index for facet v1 vertex
  31668. var b2x = 0; // X partitioning index for facet v2 vertex
  31669. var b2y = 0; // Y partitioning index for facet v2 vertex
  31670. var b2z = 0; // Z partitioning index for facet v2 vertex
  31671. var b3x = 0; // X partitioning index for facet v3 vertex
  31672. var b3y = 0; // Y partitioning index for facet v3 vertex
  31673. var b3z = 0; // Z partitioning index for facet v3 vertex
  31674. var block_idx_o = 0; // facet barycenter block index
  31675. var block_idx_v1 = 0; // v1 vertex block index
  31676. var block_idx_v2 = 0; // v2 vertex block index
  31677. var block_idx_v3 = 0; // v3 vertex block index
  31678. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31679. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31680. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31681. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31682. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31683. subSq = options.subDiv.max * options.subDiv.max;
  31684. options.facetPartitioning.length = 0;
  31685. }
  31686. // reset the normals
  31687. for (index = 0; index < positions.length; index++) {
  31688. normals[index] = 0.0;
  31689. }
  31690. // Loop : 1 indice triplet = 1 facet
  31691. var nbFaces = (indices.length / 3) | 0;
  31692. for (index = 0; index < nbFaces; index++) {
  31693. // get the indexes of the coordinates of each vertex of the facet
  31694. v1x = indices[index * 3] * 3;
  31695. v1y = v1x + 1;
  31696. v1z = v1x + 2;
  31697. v2x = indices[index * 3 + 1] * 3;
  31698. v2y = v2x + 1;
  31699. v2z = v2x + 2;
  31700. v3x = indices[index * 3 + 2] * 3;
  31701. v3y = v3x + 1;
  31702. v3z = v3x + 2;
  31703. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31704. p1p2y = positions[v1y] - positions[v2y];
  31705. p1p2z = positions[v1z] - positions[v2z];
  31706. p3p2x = positions[v3x] - positions[v2x];
  31707. p3p2y = positions[v3y] - positions[v2y];
  31708. p3p2z = positions[v3z] - positions[v2z];
  31709. // compute the face normal with the cross product
  31710. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31711. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31712. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31713. // normalize this normal and store it in the array facetData
  31714. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31715. length = (length === 0) ? 1.0 : length;
  31716. faceNormalx /= length;
  31717. faceNormaly /= length;
  31718. faceNormalz /= length;
  31719. if (computeFacetNormals && options) {
  31720. options.facetNormals[index].x = faceNormalx;
  31721. options.facetNormals[index].y = faceNormaly;
  31722. options.facetNormals[index].z = faceNormalz;
  31723. }
  31724. if (computeFacetPositions && options) {
  31725. // compute and the facet barycenter coordinates in the array facetPositions
  31726. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31727. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31728. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31729. }
  31730. if (computeFacetPartitioning && options) {
  31731. // store the facet indexes in arrays in the main facetPartitioning array :
  31732. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31733. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31734. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31735. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31736. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31737. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31738. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31739. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31740. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31741. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31742. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31743. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31744. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31745. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31746. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31747. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31748. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31749. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31750. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31751. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31752. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31753. // push each facet index in each block containing the vertex
  31754. options.facetPartitioning[block_idx_v1].push(index);
  31755. if (block_idx_v2 != block_idx_v1) {
  31756. options.facetPartitioning[block_idx_v2].push(index);
  31757. }
  31758. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31759. options.facetPartitioning[block_idx_v3].push(index);
  31760. }
  31761. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31762. options.facetPartitioning[block_idx_o].push(index);
  31763. }
  31764. }
  31765. if (computeDepthSort && options && options.facetPositions) {
  31766. var dsf = depthSortedFacets[index];
  31767. dsf.ind = index * 3;
  31768. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31769. }
  31770. // compute the normals anyway
  31771. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31772. normals[v1y] += faceNormaly;
  31773. normals[v1z] += faceNormalz;
  31774. normals[v2x] += faceNormalx;
  31775. normals[v2y] += faceNormaly;
  31776. normals[v2z] += faceNormalz;
  31777. normals[v3x] += faceNormalx;
  31778. normals[v3y] += faceNormaly;
  31779. normals[v3z] += faceNormalz;
  31780. }
  31781. // last normalization of each normal
  31782. for (index = 0; index < normals.length / 3; index++) {
  31783. faceNormalx = normals[index * 3];
  31784. faceNormaly = normals[index * 3 + 1];
  31785. faceNormalz = normals[index * 3 + 2];
  31786. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31787. length = (length === 0) ? 1.0 : length;
  31788. faceNormalx /= length;
  31789. faceNormaly /= length;
  31790. faceNormalz /= length;
  31791. normals[index * 3] = faceNormalx;
  31792. normals[index * 3 + 1] = faceNormaly;
  31793. normals[index * 3 + 2] = faceNormalz;
  31794. }
  31795. };
  31796. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31797. var li = indices.length;
  31798. var ln = normals.length;
  31799. var i;
  31800. var n;
  31801. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31802. switch (sideOrientation) {
  31803. case BABYLON.Mesh.FRONTSIDE:
  31804. // nothing changed
  31805. break;
  31806. case BABYLON.Mesh.BACKSIDE:
  31807. var tmp;
  31808. // indices
  31809. for (i = 0; i < li; i += 3) {
  31810. tmp = indices[i];
  31811. indices[i] = indices[i + 2];
  31812. indices[i + 2] = tmp;
  31813. }
  31814. // normals
  31815. for (n = 0; n < ln; n++) {
  31816. normals[n] = -normals[n];
  31817. }
  31818. break;
  31819. case BABYLON.Mesh.DOUBLESIDE:
  31820. // positions
  31821. var lp = positions.length;
  31822. var l = lp / 3;
  31823. for (var p = 0; p < lp; p++) {
  31824. positions[lp + p] = positions[p];
  31825. }
  31826. // indices
  31827. for (i = 0; i < li; i += 3) {
  31828. indices[i + li] = indices[i + 2] + l;
  31829. indices[i + 1 + li] = indices[i + 1] + l;
  31830. indices[i + 2 + li] = indices[i] + l;
  31831. }
  31832. // normals
  31833. for (n = 0; n < ln; n++) {
  31834. normals[ln + n] = -normals[n];
  31835. }
  31836. // uvs
  31837. var lu = uvs.length;
  31838. var u = 0;
  31839. for (u = 0; u < lu; u++) {
  31840. uvs[u + lu] = uvs[u];
  31841. }
  31842. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31843. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31844. u = 0;
  31845. for (i = 0; i < lu / 2; i++) {
  31846. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31847. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31848. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31849. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31850. u += 2;
  31851. }
  31852. break;
  31853. }
  31854. };
  31855. /**
  31856. * Creates a new VertexData from the imported parameters.
  31857. */
  31858. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31859. var vertexData = new VertexData();
  31860. // positions
  31861. var positions = parsedVertexData.positions;
  31862. if (positions) {
  31863. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31864. }
  31865. // normals
  31866. var normals = parsedVertexData.normals;
  31867. if (normals) {
  31868. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31869. }
  31870. // tangents
  31871. var tangents = parsedVertexData.tangents;
  31872. if (tangents) {
  31873. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31874. }
  31875. // uvs
  31876. var uvs = parsedVertexData.uvs;
  31877. if (uvs) {
  31878. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31879. }
  31880. // uv2s
  31881. var uv2s = parsedVertexData.uv2s;
  31882. if (uv2s) {
  31883. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31884. }
  31885. // uv3s
  31886. var uv3s = parsedVertexData.uv3s;
  31887. if (uv3s) {
  31888. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31889. }
  31890. // uv4s
  31891. var uv4s = parsedVertexData.uv4s;
  31892. if (uv4s) {
  31893. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31894. }
  31895. // uv5s
  31896. var uv5s = parsedVertexData.uv5s;
  31897. if (uv5s) {
  31898. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31899. }
  31900. // uv6s
  31901. var uv6s = parsedVertexData.uv6s;
  31902. if (uv6s) {
  31903. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31904. }
  31905. // colors
  31906. var colors = parsedVertexData.colors;
  31907. if (colors) {
  31908. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31909. }
  31910. // matricesIndices
  31911. var matricesIndices = parsedVertexData.matricesIndices;
  31912. if (matricesIndices) {
  31913. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31914. }
  31915. // matricesWeights
  31916. var matricesWeights = parsedVertexData.matricesWeights;
  31917. if (matricesWeights) {
  31918. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31919. }
  31920. // indices
  31921. var indices = parsedVertexData.indices;
  31922. if (indices) {
  31923. vertexData.indices = indices;
  31924. }
  31925. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31926. };
  31927. return VertexData;
  31928. }());
  31929. BABYLON.VertexData = VertexData;
  31930. })(BABYLON || (BABYLON = {}));
  31931. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31932. var BABYLON;
  31933. (function (BABYLON) {
  31934. /**
  31935. * Class used to store geometry data (vertex buffers + index buffer)
  31936. */
  31937. var Geometry = /** @class */ (function () {
  31938. /**
  31939. * Creates a new geometry
  31940. * @param id defines the unique ID
  31941. * @param scene defines the hosting scene
  31942. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  31943. * @param updatable defines if geometry must be updatable (false by default)
  31944. * @param mesh defines the mesh that will be associated with the geometry
  31945. */
  31946. function Geometry(id, scene, vertexData, updatable, mesh) {
  31947. if (updatable === void 0) { updatable = false; }
  31948. if (mesh === void 0) { mesh = null; }
  31949. /**
  31950. * Gets the delay loading state of the geometry (none by default which means not delayed)
  31951. */
  31952. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31953. this._totalVertices = 0;
  31954. this._isDisposed = false;
  31955. this._indexBufferIsUpdatable = false;
  31956. this.id = id;
  31957. this._engine = scene.getEngine();
  31958. this._meshes = [];
  31959. this._scene = scene;
  31960. //Init vertex buffer cache
  31961. this._vertexBuffers = {};
  31962. this._indices = [];
  31963. this._updatable = updatable;
  31964. // vertexData
  31965. if (vertexData) {
  31966. this.setAllVerticesData(vertexData, updatable);
  31967. }
  31968. else {
  31969. this._totalVertices = 0;
  31970. this._indices = [];
  31971. }
  31972. if (this._engine.getCaps().vertexArrayObject) {
  31973. this._vertexArrayObjects = {};
  31974. }
  31975. // applyToMesh
  31976. if (mesh) {
  31977. if (mesh.getClassName() === "LinesMesh") {
  31978. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31979. this.updateExtend();
  31980. }
  31981. this.applyToMesh(mesh);
  31982. mesh.computeWorldMatrix(true);
  31983. }
  31984. }
  31985. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31986. /**
  31987. * 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
  31988. */
  31989. get: function () {
  31990. return this._boundingBias;
  31991. },
  31992. /**
  31993. * 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
  31994. */
  31995. set: function (value) {
  31996. if (this._boundingBias && this._boundingBias.equals(value)) {
  31997. return;
  31998. }
  31999. this._boundingBias = value.clone();
  32000. this.updateBoundingInfo(true, null);
  32001. },
  32002. enumerable: true,
  32003. configurable: true
  32004. });
  32005. /**
  32006. * Static function used to attach a new empty geometry to a mesh
  32007. * @param mesh defines the mesh to attach the geometry to
  32008. * @returns the new {BABYLON.Geometry}
  32009. */
  32010. Geometry.CreateGeometryForMesh = function (mesh) {
  32011. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32012. geometry.applyToMesh(mesh);
  32013. return geometry;
  32014. };
  32015. Object.defineProperty(Geometry.prototype, "extend", {
  32016. /**
  32017. * Gets the current extend of the geometry
  32018. */
  32019. get: function () {
  32020. return this._extend;
  32021. },
  32022. enumerable: true,
  32023. configurable: true
  32024. });
  32025. /**
  32026. * Gets the hosting scene
  32027. * @returns the hosting {BABYLON.Scene}
  32028. */
  32029. Geometry.prototype.getScene = function () {
  32030. return this._scene;
  32031. };
  32032. /**
  32033. * Gets the hosting engine
  32034. * @returns the hosting {BABYLON.Engine}
  32035. */
  32036. Geometry.prototype.getEngine = function () {
  32037. return this._engine;
  32038. };
  32039. /**
  32040. * Defines if the geometry is ready to use
  32041. * @returns true if the geometry is ready to be used
  32042. */
  32043. Geometry.prototype.isReady = function () {
  32044. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32045. };
  32046. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32047. /**
  32048. * Gets a value indicating that the geometry should not be serialized
  32049. */
  32050. get: function () {
  32051. for (var index = 0; index < this._meshes.length; index++) {
  32052. if (!this._meshes[index].doNotSerialize) {
  32053. return false;
  32054. }
  32055. }
  32056. return true;
  32057. },
  32058. enumerable: true,
  32059. configurable: true
  32060. });
  32061. /** @ignore */
  32062. Geometry.prototype._rebuild = function () {
  32063. if (this._vertexArrayObjects) {
  32064. this._vertexArrayObjects = {};
  32065. }
  32066. // Index buffer
  32067. if (this._meshes.length !== 0 && this._indices) {
  32068. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32069. }
  32070. // Vertex buffers
  32071. for (var key in this._vertexBuffers) {
  32072. var vertexBuffer = this._vertexBuffers[key];
  32073. vertexBuffer._rebuild();
  32074. }
  32075. };
  32076. /**
  32077. * Affects all gemetry data in one call
  32078. * @param vertexData defines the geometry data
  32079. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32080. */
  32081. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32082. vertexData.applyToGeometry(this, updatable);
  32083. this.notifyUpdate();
  32084. };
  32085. /**
  32086. * Set specific vertex data
  32087. * @param kind defines the data kind (Position, normal, etc...)
  32088. * @param data defines the vertex data to use
  32089. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32090. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32091. */
  32092. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32093. if (updatable === void 0) { updatable = false; }
  32094. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32095. this.setVerticesBuffer(buffer);
  32096. };
  32097. /**
  32098. * Removes a specific vertex data
  32099. * @param kind defines the data kind (Position, normal, etc...)
  32100. */
  32101. Geometry.prototype.removeVerticesData = function (kind) {
  32102. if (this._vertexBuffers[kind]) {
  32103. this._vertexBuffers[kind].dispose();
  32104. delete this._vertexBuffers[kind];
  32105. }
  32106. };
  32107. /**
  32108. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32109. * @param buffer defines the vertex buffer to use
  32110. */
  32111. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32112. var kind = buffer.getKind();
  32113. if (this._vertexBuffers[kind]) {
  32114. this._vertexBuffers[kind].dispose();
  32115. }
  32116. this._vertexBuffers[kind] = buffer;
  32117. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32118. var data = buffer.getData();
  32119. var stride = buffer.getStrideSize();
  32120. this._totalVertices = data.length / stride;
  32121. this.updateExtend(data, stride);
  32122. this._resetPointsArrayCache();
  32123. var meshes = this._meshes;
  32124. var numOfMeshes = meshes.length;
  32125. for (var index = 0; index < numOfMeshes; index++) {
  32126. var mesh = meshes[index];
  32127. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32128. mesh._createGlobalSubMesh(false);
  32129. mesh.computeWorldMatrix(true);
  32130. }
  32131. }
  32132. this.notifyUpdate(kind);
  32133. if (this._vertexArrayObjects) {
  32134. this._disposeVertexArrayObjects();
  32135. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32136. }
  32137. };
  32138. /**
  32139. * Update a specific vertex buffer
  32140. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32141. * It will do nothing if the buffer is not updatable
  32142. * @param kind defines the data kind (Position, normal, etc...)
  32143. * @param data defines the data to use
  32144. * @param offset defines the offset in the target buffer where to store the data
  32145. */
  32146. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32147. var vertexBuffer = this.getVertexBuffer(kind);
  32148. if (!vertexBuffer) {
  32149. return;
  32150. }
  32151. vertexBuffer.updateDirectly(data, offset);
  32152. this.notifyUpdate(kind);
  32153. };
  32154. /**
  32155. * Update a specific vertex buffer
  32156. * This function will create a new buffer if the current one is not updatable
  32157. * @param kind defines the data kind (Position, normal, etc...)
  32158. * @param data defines the data to use
  32159. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32160. */
  32161. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32162. if (updateExtends === void 0) { updateExtends = false; }
  32163. var vertexBuffer = this.getVertexBuffer(kind);
  32164. if (!vertexBuffer) {
  32165. return;
  32166. }
  32167. vertexBuffer.update(data);
  32168. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32169. var stride = vertexBuffer.getStrideSize();
  32170. this._totalVertices = data.length / stride;
  32171. this.updateBoundingInfo(updateExtends, data);
  32172. }
  32173. this.notifyUpdate(kind);
  32174. };
  32175. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32176. if (updateExtends) {
  32177. this.updateExtend(data);
  32178. }
  32179. var meshes = this._meshes;
  32180. var numOfMeshes = meshes.length;
  32181. this._resetPointsArrayCache();
  32182. for (var index = 0; index < numOfMeshes; index++) {
  32183. var mesh = meshes[index];
  32184. if (updateExtends) {
  32185. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32186. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32187. var subMesh = mesh.subMeshes[subIndex];
  32188. subMesh.refreshBoundingInfo();
  32189. }
  32190. }
  32191. }
  32192. };
  32193. /** @ignore */
  32194. Geometry.prototype._bind = function (effect, indexToBind) {
  32195. if (!effect) {
  32196. return;
  32197. }
  32198. if (indexToBind === undefined) {
  32199. indexToBind = this._indexBuffer;
  32200. }
  32201. var vbs = this.getVertexBuffers();
  32202. if (!vbs) {
  32203. return;
  32204. }
  32205. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32206. this._engine.bindBuffers(vbs, indexToBind, effect);
  32207. return;
  32208. }
  32209. // Using VAO
  32210. if (!this._vertexArrayObjects[effect.key]) {
  32211. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32212. }
  32213. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32214. };
  32215. /**
  32216. * Gets total number of vertices
  32217. * @returns the total number of vertices
  32218. */
  32219. Geometry.prototype.getTotalVertices = function () {
  32220. if (!this.isReady()) {
  32221. return 0;
  32222. }
  32223. return this._totalVertices;
  32224. };
  32225. /**
  32226. * Gets a specific vertex data attached to this geometry
  32227. * @param kind defines the data kind (Position, normal, etc...)
  32228. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32229. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32230. * @returns a float array containing vertex data
  32231. */
  32232. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32233. var vertexBuffer = this.getVertexBuffer(kind);
  32234. if (!vertexBuffer) {
  32235. return null;
  32236. }
  32237. var orig = vertexBuffer.getData();
  32238. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32239. return orig;
  32240. }
  32241. else {
  32242. var len = orig.length;
  32243. var copy = [];
  32244. for (var i = 0; i < len; i++) {
  32245. copy.push(orig[i]);
  32246. }
  32247. return copy;
  32248. }
  32249. };
  32250. /**
  32251. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32252. * @param kind defines the data kind (Position, normal, etc...)
  32253. * @returns true if the vertex buffer with the specified kind is updatable
  32254. */
  32255. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32256. var vb = this._vertexBuffers[kind];
  32257. if (!vb) {
  32258. return false;
  32259. }
  32260. return vb.isUpdatable();
  32261. };
  32262. /**
  32263. * Gets a specific vertex buffer
  32264. * @param kind defines the data kind (Position, normal, etc...)
  32265. * @returns a {BABYLON.VertexBuffer}
  32266. */
  32267. Geometry.prototype.getVertexBuffer = function (kind) {
  32268. if (!this.isReady()) {
  32269. return null;
  32270. }
  32271. return this._vertexBuffers[kind];
  32272. };
  32273. /**
  32274. * Returns all vertex buffers
  32275. * @return an object holding all vertex buffers indexed by kind
  32276. */
  32277. Geometry.prototype.getVertexBuffers = function () {
  32278. if (!this.isReady()) {
  32279. return null;
  32280. }
  32281. return this._vertexBuffers;
  32282. };
  32283. /**
  32284. * Gets a boolean indicating if specific vertex buffer is present
  32285. * @param kind defines the data kind (Position, normal, etc...)
  32286. * @returns true if data is present
  32287. */
  32288. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32289. if (!this._vertexBuffers) {
  32290. if (this._delayInfo) {
  32291. return this._delayInfo.indexOf(kind) !== -1;
  32292. }
  32293. return false;
  32294. }
  32295. return this._vertexBuffers[kind] !== undefined;
  32296. };
  32297. /**
  32298. * Gets a list of all attached data kinds (Position, normal, etc...)
  32299. * @returns a list of string containing all kinds
  32300. */
  32301. Geometry.prototype.getVerticesDataKinds = function () {
  32302. var result = [];
  32303. var kind;
  32304. if (!this._vertexBuffers && this._delayInfo) {
  32305. for (kind in this._delayInfo) {
  32306. result.push(kind);
  32307. }
  32308. }
  32309. else {
  32310. for (kind in this._vertexBuffers) {
  32311. result.push(kind);
  32312. }
  32313. }
  32314. return result;
  32315. };
  32316. /**
  32317. * Update index buffer
  32318. * @param indices defines the indices to store in the index buffer
  32319. * @param offset defines the offset in the target buffer where to store the data
  32320. */
  32321. Geometry.prototype.updateIndices = function (indices, offset) {
  32322. if (!this._indexBuffer) {
  32323. return;
  32324. }
  32325. if (!this._indexBufferIsUpdatable) {
  32326. this.setIndices(indices, null, true);
  32327. }
  32328. else {
  32329. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32330. }
  32331. };
  32332. /**
  32333. * Creates a new index buffer
  32334. * @param indices defines the indices to store in the index buffer
  32335. * @param totalVertices defines the total number of vertices (could be null)
  32336. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32337. */
  32338. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32339. if (totalVertices === void 0) { totalVertices = null; }
  32340. if (updatable === void 0) { updatable = false; }
  32341. if (this._indexBuffer) {
  32342. this._engine._releaseBuffer(this._indexBuffer);
  32343. }
  32344. this._disposeVertexArrayObjects();
  32345. this._indices = indices;
  32346. this._indexBufferIsUpdatable = updatable;
  32347. if (this._meshes.length !== 0 && this._indices) {
  32348. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32349. }
  32350. if (totalVertices != undefined) {
  32351. this._totalVertices = totalVertices;
  32352. }
  32353. var meshes = this._meshes;
  32354. var numOfMeshes = meshes.length;
  32355. for (var index = 0; index < numOfMeshes; index++) {
  32356. meshes[index]._createGlobalSubMesh(true);
  32357. }
  32358. this.notifyUpdate();
  32359. };
  32360. /**
  32361. * Return the total number of indices
  32362. * @returns the total number of indices
  32363. */
  32364. Geometry.prototype.getTotalIndices = function () {
  32365. if (!this.isReady()) {
  32366. return 0;
  32367. }
  32368. return this._indices.length;
  32369. };
  32370. /**
  32371. * Gets the index buffer array
  32372. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32373. * @returns the index buffer array
  32374. */
  32375. Geometry.prototype.getIndices = function (copyWhenShared) {
  32376. if (!this.isReady()) {
  32377. return null;
  32378. }
  32379. var orig = this._indices;
  32380. if (!copyWhenShared || this._meshes.length === 1) {
  32381. return orig;
  32382. }
  32383. else {
  32384. var len = orig.length;
  32385. var copy = [];
  32386. for (var i = 0; i < len; i++) {
  32387. copy.push(orig[i]);
  32388. }
  32389. return copy;
  32390. }
  32391. };
  32392. /**
  32393. * Gets the index buffer
  32394. * @return the index buffer
  32395. */
  32396. Geometry.prototype.getIndexBuffer = function () {
  32397. if (!this.isReady()) {
  32398. return null;
  32399. }
  32400. return this._indexBuffer;
  32401. };
  32402. /** @ignore */
  32403. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32404. if (effect === void 0) { effect = null; }
  32405. if (!effect || !this._vertexArrayObjects) {
  32406. return;
  32407. }
  32408. if (this._vertexArrayObjects[effect.key]) {
  32409. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32410. delete this._vertexArrayObjects[effect.key];
  32411. }
  32412. };
  32413. /**
  32414. * Release the associated resources for a specific mesh
  32415. * @param mesh defines the source mesh
  32416. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32417. */
  32418. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32419. var meshes = this._meshes;
  32420. var index = meshes.indexOf(mesh);
  32421. if (index === -1) {
  32422. return;
  32423. }
  32424. meshes.splice(index, 1);
  32425. mesh._geometry = null;
  32426. if (meshes.length === 0 && shouldDispose) {
  32427. this.dispose();
  32428. }
  32429. };
  32430. /**
  32431. * Apply current geometry to a given mesh
  32432. * @param mesh defines the mesh to apply geometry to
  32433. */
  32434. Geometry.prototype.applyToMesh = function (mesh) {
  32435. if (mesh._geometry === this) {
  32436. return;
  32437. }
  32438. var previousGeometry = mesh._geometry;
  32439. if (previousGeometry) {
  32440. previousGeometry.releaseForMesh(mesh);
  32441. }
  32442. var meshes = this._meshes;
  32443. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32444. mesh._geometry = this;
  32445. this._scene.pushGeometry(this);
  32446. meshes.push(mesh);
  32447. if (this.isReady()) {
  32448. this._applyToMesh(mesh);
  32449. }
  32450. else {
  32451. mesh._boundingInfo = this._boundingInfo;
  32452. }
  32453. };
  32454. Geometry.prototype.updateExtend = function (data, stride) {
  32455. if (data === void 0) { data = null; }
  32456. if (!data) {
  32457. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32458. }
  32459. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32460. };
  32461. Geometry.prototype._applyToMesh = function (mesh) {
  32462. var numOfMeshes = this._meshes.length;
  32463. // vertexBuffers
  32464. for (var kind in this._vertexBuffers) {
  32465. if (numOfMeshes === 1) {
  32466. this._vertexBuffers[kind].create();
  32467. }
  32468. var buffer = this._vertexBuffers[kind].getBuffer();
  32469. if (buffer)
  32470. buffer.references = numOfMeshes;
  32471. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32472. if (!this._extend) {
  32473. this.updateExtend(this._vertexBuffers[kind].getData());
  32474. }
  32475. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32476. mesh._createGlobalSubMesh(false);
  32477. //bounding info was just created again, world matrix should be applied again.
  32478. mesh._updateBoundingInfo();
  32479. }
  32480. }
  32481. // indexBuffer
  32482. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32483. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32484. }
  32485. if (this._indexBuffer) {
  32486. this._indexBuffer.references = numOfMeshes;
  32487. }
  32488. };
  32489. Geometry.prototype.notifyUpdate = function (kind) {
  32490. if (this.onGeometryUpdated) {
  32491. this.onGeometryUpdated(this, kind);
  32492. }
  32493. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32494. var mesh = _a[_i];
  32495. mesh._markSubMeshesAsAttributesDirty();
  32496. }
  32497. };
  32498. /**
  32499. * Load the geometry if it was flagged as delay loaded
  32500. * @param scene defines the hosting scene
  32501. * @param onLoaded defines a callback called when the geometry is loaded
  32502. */
  32503. Geometry.prototype.load = function (scene, onLoaded) {
  32504. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32505. return;
  32506. }
  32507. if (this.isReady()) {
  32508. if (onLoaded) {
  32509. onLoaded();
  32510. }
  32511. return;
  32512. }
  32513. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32514. this._queueLoad(scene, onLoaded);
  32515. };
  32516. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32517. var _this = this;
  32518. if (!this.delayLoadingFile) {
  32519. return;
  32520. }
  32521. scene._addPendingData(this);
  32522. scene._loadFile(this.delayLoadingFile, function (data) {
  32523. if (!_this._delayLoadingFunction) {
  32524. return;
  32525. }
  32526. _this._delayLoadingFunction(JSON.parse(data), _this);
  32527. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32528. _this._delayInfo = [];
  32529. scene._removePendingData(_this);
  32530. var meshes = _this._meshes;
  32531. var numOfMeshes = meshes.length;
  32532. for (var index = 0; index < numOfMeshes; index++) {
  32533. _this._applyToMesh(meshes[index]);
  32534. }
  32535. if (onLoaded) {
  32536. onLoaded();
  32537. }
  32538. }, undefined, true);
  32539. };
  32540. /**
  32541. * Invert the geometry to move from a right handed system to a left handed one.
  32542. */
  32543. Geometry.prototype.toLeftHanded = function () {
  32544. // Flip faces
  32545. var tIndices = this.getIndices(false);
  32546. if (tIndices != null && tIndices.length > 0) {
  32547. for (var i = 0; i < tIndices.length; i += 3) {
  32548. var tTemp = tIndices[i + 0];
  32549. tIndices[i + 0] = tIndices[i + 2];
  32550. tIndices[i + 2] = tTemp;
  32551. }
  32552. this.setIndices(tIndices);
  32553. }
  32554. // Negate position.z
  32555. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32556. if (tPositions != null && tPositions.length > 0) {
  32557. for (var i = 0; i < tPositions.length; i += 3) {
  32558. tPositions[i + 2] = -tPositions[i + 2];
  32559. }
  32560. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32561. }
  32562. // Negate normal.z
  32563. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32564. if (tNormals != null && tNormals.length > 0) {
  32565. for (var i = 0; i < tNormals.length; i += 3) {
  32566. tNormals[i + 2] = -tNormals[i + 2];
  32567. }
  32568. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32569. }
  32570. };
  32571. // Cache
  32572. /** @ignore */
  32573. Geometry.prototype._resetPointsArrayCache = function () {
  32574. this._positions = null;
  32575. };
  32576. /** @ignore */
  32577. Geometry.prototype._generatePointsArray = function () {
  32578. if (this._positions)
  32579. return true;
  32580. this._positions = [];
  32581. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32582. if (!data) {
  32583. return false;
  32584. }
  32585. for (var index = 0; index < data.length; index += 3) {
  32586. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32587. }
  32588. return true;
  32589. };
  32590. /**
  32591. * Gets a value indicating if the geometry is disposed
  32592. * @returns true if the geometry was disposed
  32593. */
  32594. Geometry.prototype.isDisposed = function () {
  32595. return this._isDisposed;
  32596. };
  32597. Geometry.prototype._disposeVertexArrayObjects = function () {
  32598. if (this._vertexArrayObjects) {
  32599. for (var kind in this._vertexArrayObjects) {
  32600. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32601. }
  32602. this._vertexArrayObjects = {};
  32603. }
  32604. };
  32605. /**
  32606. * Free all associated resources
  32607. */
  32608. Geometry.prototype.dispose = function () {
  32609. var meshes = this._meshes;
  32610. var numOfMeshes = meshes.length;
  32611. var index;
  32612. for (index = 0; index < numOfMeshes; index++) {
  32613. this.releaseForMesh(meshes[index]);
  32614. }
  32615. this._meshes = [];
  32616. this._disposeVertexArrayObjects();
  32617. for (var kind in this._vertexBuffers) {
  32618. this._vertexBuffers[kind].dispose();
  32619. }
  32620. this._vertexBuffers = {};
  32621. this._totalVertices = 0;
  32622. if (this._indexBuffer) {
  32623. this._engine._releaseBuffer(this._indexBuffer);
  32624. }
  32625. this._indexBuffer = null;
  32626. this._indices = [];
  32627. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32628. this.delayLoadingFile = null;
  32629. this._delayLoadingFunction = null;
  32630. this._delayInfo = [];
  32631. this._boundingInfo = null;
  32632. this._scene.removeGeometry(this);
  32633. this._isDisposed = true;
  32634. };
  32635. /**
  32636. * Clone the current geometry into a new geometry
  32637. * @param id defines the unique ID of the new geometry
  32638. * @returns a new geometry object
  32639. */
  32640. Geometry.prototype.copy = function (id) {
  32641. var vertexData = new BABYLON.VertexData();
  32642. vertexData.indices = [];
  32643. var indices = this.getIndices();
  32644. if (indices) {
  32645. for (var index = 0; index < indices.length; index++) {
  32646. vertexData.indices.push(indices[index]);
  32647. }
  32648. }
  32649. var updatable = false;
  32650. var stopChecking = false;
  32651. var kind;
  32652. for (kind in this._vertexBuffers) {
  32653. // using slice() to make a copy of the array and not just reference it
  32654. var data = this.getVerticesData(kind);
  32655. if (data instanceof Float32Array) {
  32656. vertexData.set(new Float32Array(data), kind);
  32657. }
  32658. else {
  32659. vertexData.set(data.slice(0), kind);
  32660. }
  32661. if (!stopChecking) {
  32662. var vb = this.getVertexBuffer(kind);
  32663. if (vb) {
  32664. updatable = vb.isUpdatable();
  32665. stopChecking = !updatable;
  32666. }
  32667. }
  32668. }
  32669. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32670. geometry.delayLoadState = this.delayLoadState;
  32671. geometry.delayLoadingFile = this.delayLoadingFile;
  32672. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32673. for (kind in this._delayInfo) {
  32674. geometry._delayInfo = geometry._delayInfo || [];
  32675. geometry._delayInfo.push(kind);
  32676. }
  32677. // Bounding info
  32678. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32679. return geometry;
  32680. };
  32681. /**
  32682. * Serialize the current geometry info (and not the vertices data) into a JSON object
  32683. * @return a JSON representation of the current geometry data (without the vertices data)
  32684. */
  32685. Geometry.prototype.serialize = function () {
  32686. var serializationObject = {};
  32687. serializationObject.id = this.id;
  32688. serializationObject.updatable = this._updatable;
  32689. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32690. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32691. }
  32692. return serializationObject;
  32693. };
  32694. Geometry.prototype.toNumberArray = function (origin) {
  32695. if (Array.isArray(origin)) {
  32696. return origin;
  32697. }
  32698. else {
  32699. return Array.prototype.slice.call(origin);
  32700. }
  32701. };
  32702. /**
  32703. * Serialize all vertices data into a JSON oject
  32704. * @returns a JSON representation of the current geometry data
  32705. */
  32706. Geometry.prototype.serializeVerticeData = function () {
  32707. var serializationObject = this.serialize();
  32708. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32709. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32710. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32711. serializationObject.positions._updatable = true;
  32712. }
  32713. }
  32714. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32715. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32716. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32717. serializationObject.normals._updatable = true;
  32718. }
  32719. }
  32720. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32721. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  32722. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  32723. serializationObject.tangets._updatable = true;
  32724. }
  32725. }
  32726. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32727. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32728. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32729. serializationObject.uvs._updatable = true;
  32730. }
  32731. }
  32732. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32733. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32734. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32735. serializationObject.uv2s._updatable = true;
  32736. }
  32737. }
  32738. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32739. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32740. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32741. serializationObject.uv3s._updatable = true;
  32742. }
  32743. }
  32744. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32745. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32746. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32747. serializationObject.uv4s._updatable = true;
  32748. }
  32749. }
  32750. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32751. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32752. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32753. serializationObject.uv5s._updatable = true;
  32754. }
  32755. }
  32756. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32757. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32758. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32759. serializationObject.uv6s._updatable = true;
  32760. }
  32761. }
  32762. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32763. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32764. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32765. serializationObject.colors._updatable = true;
  32766. }
  32767. }
  32768. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32769. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32770. serializationObject.matricesIndices._isExpanded = true;
  32771. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32772. serializationObject.matricesIndices._updatable = true;
  32773. }
  32774. }
  32775. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32776. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32777. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32778. serializationObject.matricesWeights._updatable = true;
  32779. }
  32780. }
  32781. serializationObject.indices = this.toNumberArray(this.getIndices());
  32782. return serializationObject;
  32783. };
  32784. // Statics
  32785. /**
  32786. * Extracts a clone of a mesh geometry
  32787. * @param mesh defines the source mesh
  32788. * @param id defines the unique ID of the new geometry object
  32789. * @returns the new geometry object
  32790. */
  32791. Geometry.ExtractFromMesh = function (mesh, id) {
  32792. var geometry = mesh._geometry;
  32793. if (!geometry) {
  32794. return null;
  32795. }
  32796. return geometry.copy(id);
  32797. };
  32798. /**
  32799. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32800. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32801. * Be aware Math.random() could cause collisions, but:
  32802. * "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"
  32803. * @returns a string containing a new GUID
  32804. */
  32805. Geometry.RandomId = function () {
  32806. return BABYLON.Tools.RandomId();
  32807. };
  32808. /** @ignore */
  32809. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  32810. var scene = mesh.getScene();
  32811. // Geometry
  32812. var geometryId = parsedGeometry.geometryId;
  32813. if (geometryId) {
  32814. var geometry = scene.getGeometryByID(geometryId);
  32815. if (geometry) {
  32816. geometry.applyToMesh(mesh);
  32817. }
  32818. }
  32819. else if (parsedGeometry instanceof ArrayBuffer) {
  32820. var binaryInfo = mesh._binaryInfo;
  32821. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32822. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32823. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32824. }
  32825. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32826. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32827. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32828. }
  32829. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  32830. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  32831. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  32832. }
  32833. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32834. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32835. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32836. }
  32837. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32838. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32839. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32840. }
  32841. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32842. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32843. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32844. }
  32845. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32846. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32847. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32848. }
  32849. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32850. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32851. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32852. }
  32853. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32854. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32855. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32856. }
  32857. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32858. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32859. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32860. }
  32861. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32862. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32863. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32864. }
  32865. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32866. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32867. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32868. }
  32869. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32870. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32871. mesh.setIndices(indicesData, null);
  32872. }
  32873. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32874. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32875. mesh.subMeshes = [];
  32876. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32877. var materialIndex = subMeshesData[(i * 5) + 0];
  32878. var verticesStart = subMeshesData[(i * 5) + 1];
  32879. var verticesCount = subMeshesData[(i * 5) + 2];
  32880. var indexStart = subMeshesData[(i * 5) + 3];
  32881. var indexCount = subMeshesData[(i * 5) + 4];
  32882. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32883. }
  32884. }
  32885. }
  32886. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32887. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32888. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32889. if (parsedGeometry.tangents) {
  32890. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  32891. }
  32892. if (parsedGeometry.uvs) {
  32893. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32894. }
  32895. if (parsedGeometry.uvs2) {
  32896. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32897. }
  32898. if (parsedGeometry.uvs3) {
  32899. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32900. }
  32901. if (parsedGeometry.uvs4) {
  32902. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32903. }
  32904. if (parsedGeometry.uvs5) {
  32905. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32906. }
  32907. if (parsedGeometry.uvs6) {
  32908. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32909. }
  32910. if (parsedGeometry.colors) {
  32911. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32912. }
  32913. if (parsedGeometry.matricesIndices) {
  32914. if (!parsedGeometry.matricesIndices._isExpanded) {
  32915. var floatIndices = [];
  32916. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32917. var matricesIndex = parsedGeometry.matricesIndices[i];
  32918. floatIndices.push(matricesIndex & 0x000000FF);
  32919. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32920. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32921. floatIndices.push(matricesIndex >> 24);
  32922. }
  32923. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32924. }
  32925. else {
  32926. delete parsedGeometry.matricesIndices._isExpanded;
  32927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32928. }
  32929. }
  32930. if (parsedGeometry.matricesIndicesExtra) {
  32931. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32932. var floatIndices = [];
  32933. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32934. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32935. floatIndices.push(matricesIndex & 0x000000FF);
  32936. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32937. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32938. floatIndices.push(matricesIndex >> 24);
  32939. }
  32940. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32941. }
  32942. else {
  32943. delete parsedGeometry.matricesIndices._isExpanded;
  32944. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32945. }
  32946. }
  32947. if (parsedGeometry.matricesWeights) {
  32948. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32949. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32950. }
  32951. if (parsedGeometry.matricesWeightsExtra) {
  32952. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32953. }
  32954. mesh.setIndices(parsedGeometry.indices, null);
  32955. }
  32956. // SubMeshes
  32957. if (parsedGeometry.subMeshes) {
  32958. mesh.subMeshes = [];
  32959. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32960. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32961. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32962. }
  32963. }
  32964. // Flat shading
  32965. if (mesh._shouldGenerateFlatShading) {
  32966. mesh.convertToFlatShadedMesh();
  32967. delete mesh._shouldGenerateFlatShading;
  32968. }
  32969. // Update
  32970. mesh.computeWorldMatrix(true);
  32971. // Octree
  32972. var sceneOctree = scene.selectionOctree;
  32973. if (sceneOctree !== undefined && sceneOctree !== null) {
  32974. sceneOctree.addMesh(mesh);
  32975. }
  32976. };
  32977. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32978. var epsilon = 1e-3;
  32979. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32980. return;
  32981. }
  32982. var noInfluenceBoneIndex = 0.0;
  32983. if (parsedGeometry.skeletonId > -1) {
  32984. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32985. if (!skeleton) {
  32986. return;
  32987. }
  32988. noInfluenceBoneIndex = skeleton.bones.length;
  32989. }
  32990. else {
  32991. return;
  32992. }
  32993. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32994. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32995. var matricesWeights = parsedGeometry.matricesWeights;
  32996. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32997. var influencers = parsedGeometry.numBoneInfluencer;
  32998. var size = matricesWeights.length;
  32999. for (var i = 0; i < size; i += 4) {
  33000. var weight = 0.0;
  33001. var firstZeroWeight = -1;
  33002. for (var j = 0; j < 4; j++) {
  33003. var w = matricesWeights[i + j];
  33004. weight += w;
  33005. if (w < epsilon && firstZeroWeight < 0) {
  33006. firstZeroWeight = j;
  33007. }
  33008. }
  33009. if (matricesWeightsExtra) {
  33010. for (var j = 0; j < 4; j++) {
  33011. var w = matricesWeightsExtra[i + j];
  33012. weight += w;
  33013. if (w < epsilon && firstZeroWeight < 0) {
  33014. firstZeroWeight = j + 4;
  33015. }
  33016. }
  33017. }
  33018. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33019. firstZeroWeight = influencers - 1;
  33020. }
  33021. if (weight > epsilon) {
  33022. var mweight = 1.0 / weight;
  33023. for (var j = 0; j < 4; j++) {
  33024. matricesWeights[i + j] *= mweight;
  33025. }
  33026. if (matricesWeightsExtra) {
  33027. for (var j = 0; j < 4; j++) {
  33028. matricesWeightsExtra[i + j] *= mweight;
  33029. }
  33030. }
  33031. }
  33032. else {
  33033. if (firstZeroWeight >= 4) {
  33034. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33035. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33036. }
  33037. else {
  33038. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33039. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33040. }
  33041. }
  33042. }
  33043. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33044. if (parsedGeometry.matricesWeightsExtra) {
  33045. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33046. }
  33047. };
  33048. /**
  33049. * Create a new geometry from persisted data (Using .babylon file format)
  33050. * @param parsedVertexData defines the persisted data
  33051. * @param scene defines the hosting scene
  33052. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33053. * @returns the new geometry object
  33054. */
  33055. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33056. if (scene.getGeometryByID(parsedVertexData.id)) {
  33057. return null; // null since geometry could be something else than a box...
  33058. }
  33059. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33060. if (BABYLON.Tags) {
  33061. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33062. }
  33063. if (parsedVertexData.delayLoadingFile) {
  33064. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33065. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33066. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33067. geometry._delayInfo = [];
  33068. if (parsedVertexData.hasUVs) {
  33069. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33070. }
  33071. if (parsedVertexData.hasUVs2) {
  33072. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33073. }
  33074. if (parsedVertexData.hasUVs3) {
  33075. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33076. }
  33077. if (parsedVertexData.hasUVs4) {
  33078. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33079. }
  33080. if (parsedVertexData.hasUVs5) {
  33081. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33082. }
  33083. if (parsedVertexData.hasUVs6) {
  33084. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33085. }
  33086. if (parsedVertexData.hasColors) {
  33087. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33088. }
  33089. if (parsedVertexData.hasMatricesIndices) {
  33090. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33091. }
  33092. if (parsedVertexData.hasMatricesWeights) {
  33093. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33094. }
  33095. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33096. }
  33097. else {
  33098. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33099. }
  33100. scene.pushGeometry(geometry, true);
  33101. return geometry;
  33102. };
  33103. return Geometry;
  33104. }());
  33105. BABYLON.Geometry = Geometry;
  33106. // Primitives
  33107. /// Abstract class
  33108. /**
  33109. * Abstract class used to provide common services for all typed geometries
  33110. */
  33111. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33112. __extends(_PrimitiveGeometry, _super);
  33113. /**
  33114. * Creates a new typed geometry
  33115. * @param id defines the unique ID of the geometry
  33116. * @param scene defines the hosting scene
  33117. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33118. * @param mesh defines the hosting mesh (can be null)
  33119. */
  33120. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33121. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33122. if (mesh === void 0) { mesh = null; }
  33123. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33124. _this._canBeRegenerated = _canBeRegenerated;
  33125. _this._beingRegenerated = true;
  33126. _this.regenerate();
  33127. _this._beingRegenerated = false;
  33128. return _this;
  33129. }
  33130. /**
  33131. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33132. * @returns true if the geometry can be regenerated
  33133. */
  33134. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33135. return this._canBeRegenerated;
  33136. };
  33137. /**
  33138. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33139. */
  33140. _PrimitiveGeometry.prototype.regenerate = function () {
  33141. if (!this._canBeRegenerated) {
  33142. return;
  33143. }
  33144. this._beingRegenerated = true;
  33145. this.setAllVerticesData(this._regenerateVertexData(), false);
  33146. this._beingRegenerated = false;
  33147. };
  33148. /**
  33149. * Clone the geometry
  33150. * @param id defines the unique ID of the new geometry
  33151. * @returns the new geometry
  33152. */
  33153. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33154. return _super.prototype.copy.call(this, id);
  33155. };
  33156. // overrides
  33157. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33158. if (!this._beingRegenerated) {
  33159. return;
  33160. }
  33161. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33162. };
  33163. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33164. if (!this._beingRegenerated) {
  33165. return;
  33166. }
  33167. _super.prototype.setVerticesData.call(this, kind, data, false);
  33168. };
  33169. // to override
  33170. /** @ignore */
  33171. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33172. throw new Error("Abstract method");
  33173. };
  33174. _PrimitiveGeometry.prototype.copy = function (id) {
  33175. throw new Error("Must be overriden in sub-classes.");
  33176. };
  33177. _PrimitiveGeometry.prototype.serialize = function () {
  33178. var serializationObject = _super.prototype.serialize.call(this);
  33179. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33180. return serializationObject;
  33181. };
  33182. return _PrimitiveGeometry;
  33183. }(Geometry));
  33184. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33185. /**
  33186. * Creates a ribbon geometry
  33187. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33188. */
  33189. var RibbonGeometry = /** @class */ (function (_super) {
  33190. __extends(RibbonGeometry, _super);
  33191. /**
  33192. * Creates a ribbon geometry
  33193. * @param id defines the unique ID of the geometry
  33194. * @param scene defines the hosting scene
  33195. * @param pathArray defines the array of paths to use
  33196. * @param closeArray defines if the last path and the first path must be joined
  33197. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33198. * @param offset defines the offset between points
  33199. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33200. * @param mesh defines the hosting mesh (can be null)
  33201. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33202. */
  33203. function RibbonGeometry(id, scene,
  33204. /**
  33205. * Defines the array of paths to use
  33206. */
  33207. pathArray,
  33208. /**
  33209. * Defines if the last and first points of each path in your pathArray must be joined
  33210. */
  33211. closeArray,
  33212. /**
  33213. * Defines if the last and first points of each path in your pathArray must be joined
  33214. */
  33215. closePath,
  33216. /**
  33217. * Defines the offset between points
  33218. */
  33219. offset, canBeRegenerated, mesh,
  33220. /**
  33221. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33222. */
  33223. side) {
  33224. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33225. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33226. _this.pathArray = pathArray;
  33227. _this.closeArray = closeArray;
  33228. _this.closePath = closePath;
  33229. _this.offset = offset;
  33230. _this.side = side;
  33231. return _this;
  33232. }
  33233. /** @ignore */
  33234. RibbonGeometry.prototype._regenerateVertexData = function () {
  33235. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33236. };
  33237. RibbonGeometry.prototype.copy = function (id) {
  33238. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33239. };
  33240. return RibbonGeometry;
  33241. }(_PrimitiveGeometry));
  33242. BABYLON.RibbonGeometry = RibbonGeometry;
  33243. /**
  33244. * Creates a box geometry
  33245. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33246. */
  33247. var BoxGeometry = /** @class */ (function (_super) {
  33248. __extends(BoxGeometry, _super);
  33249. /**
  33250. * Creates a box geometry
  33251. * @param id defines the unique ID of the geometry
  33252. * @param scene defines the hosting scene
  33253. * @param size defines the zise of the box (width, height and depth are the same)
  33254. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33255. * @param mesh defines the hosting mesh (can be null)
  33256. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33257. */
  33258. function BoxGeometry(id, scene,
  33259. /**
  33260. * Defines the zise of the box (width, height and depth are the same)
  33261. */
  33262. size, canBeRegenerated, mesh,
  33263. /**
  33264. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33265. */
  33266. side) {
  33267. if (mesh === void 0) { mesh = null; }
  33268. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33269. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33270. _this.size = size;
  33271. _this.side = side;
  33272. return _this;
  33273. }
  33274. BoxGeometry.prototype._regenerateVertexData = function () {
  33275. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33276. };
  33277. BoxGeometry.prototype.copy = function (id) {
  33278. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33279. };
  33280. BoxGeometry.prototype.serialize = function () {
  33281. var serializationObject = _super.prototype.serialize.call(this);
  33282. serializationObject.size = this.size;
  33283. return serializationObject;
  33284. };
  33285. BoxGeometry.Parse = function (parsedBox, scene) {
  33286. if (scene.getGeometryByID(parsedBox.id)) {
  33287. return null; // null since geometry could be something else than a box...
  33288. }
  33289. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33290. if (BABYLON.Tags) {
  33291. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33292. }
  33293. scene.pushGeometry(box, true);
  33294. return box;
  33295. };
  33296. return BoxGeometry;
  33297. }(_PrimitiveGeometry));
  33298. BABYLON.BoxGeometry = BoxGeometry;
  33299. /**
  33300. * Creates a sphere geometry
  33301. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33302. */
  33303. var SphereGeometry = /** @class */ (function (_super) {
  33304. __extends(SphereGeometry, _super);
  33305. /**
  33306. * Create a new sphere geometry
  33307. * @param id defines the unique ID of the geometry
  33308. * @param scene defines the hosting scene
  33309. * @param segments defines the number of segments to use to create the sphere
  33310. * @param diameter defines the diameter of the sphere
  33311. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33312. * @param mesh defines the hosting mesh (can be null)
  33313. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33314. */
  33315. function SphereGeometry(id, scene,
  33316. /**
  33317. * Defines the number of segments to use to create the sphere
  33318. */
  33319. segments,
  33320. /**
  33321. * Defines the diameter of the sphere
  33322. */
  33323. diameter, canBeRegenerated, mesh,
  33324. /**
  33325. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33326. */
  33327. side) {
  33328. if (mesh === void 0) { mesh = null; }
  33329. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33330. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33331. _this.segments = segments;
  33332. _this.diameter = diameter;
  33333. _this.side = side;
  33334. return _this;
  33335. }
  33336. SphereGeometry.prototype._regenerateVertexData = function () {
  33337. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33338. };
  33339. SphereGeometry.prototype.copy = function (id) {
  33340. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33341. };
  33342. SphereGeometry.prototype.serialize = function () {
  33343. var serializationObject = _super.prototype.serialize.call(this);
  33344. serializationObject.segments = this.segments;
  33345. serializationObject.diameter = this.diameter;
  33346. return serializationObject;
  33347. };
  33348. SphereGeometry.Parse = function (parsedSphere, scene) {
  33349. if (scene.getGeometryByID(parsedSphere.id)) {
  33350. return null; // null since geometry could be something else than a sphere...
  33351. }
  33352. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33353. if (BABYLON.Tags) {
  33354. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33355. }
  33356. scene.pushGeometry(sphere, true);
  33357. return sphere;
  33358. };
  33359. return SphereGeometry;
  33360. }(_PrimitiveGeometry));
  33361. BABYLON.SphereGeometry = SphereGeometry;
  33362. /**
  33363. * Creates a disc geometry
  33364. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33365. */
  33366. var DiscGeometry = /** @class */ (function (_super) {
  33367. __extends(DiscGeometry, _super);
  33368. /**
  33369. * Creates a new disc geometry
  33370. * @param id defines the unique ID of the geometry
  33371. * @param scene defines the hosting scene
  33372. * @param radius defines the radius of the disc
  33373. * @param tessellation defines the tesselation factor to apply to the disc
  33374. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33375. * @param mesh defines the hosting mesh (can be null)
  33376. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33377. */
  33378. function DiscGeometry(id, scene,
  33379. /**
  33380. * Defines the radius of the disc
  33381. */
  33382. radius,
  33383. /**
  33384. * Defines the tesselation factor to apply to the disc
  33385. */
  33386. tessellation, canBeRegenerated, mesh,
  33387. /**
  33388. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33389. */
  33390. side) {
  33391. if (mesh === void 0) { mesh = null; }
  33392. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33393. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33394. _this.radius = radius;
  33395. _this.tessellation = tessellation;
  33396. _this.side = side;
  33397. return _this;
  33398. }
  33399. DiscGeometry.prototype._regenerateVertexData = function () {
  33400. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33401. };
  33402. DiscGeometry.prototype.copy = function (id) {
  33403. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33404. };
  33405. return DiscGeometry;
  33406. }(_PrimitiveGeometry));
  33407. BABYLON.DiscGeometry = DiscGeometry;
  33408. /**
  33409. * Creates a new cylinder geometry
  33410. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33411. */
  33412. var CylinderGeometry = /** @class */ (function (_super) {
  33413. __extends(CylinderGeometry, _super);
  33414. /**
  33415. * Creates a new cylinder geometry
  33416. * @param id defines the unique ID of the geometry
  33417. * @param scene defines the hosting scene
  33418. * @param height defines the height of the cylinder
  33419. * @param diameterTop defines the diameter of the cylinder's top cap
  33420. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33421. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33422. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33423. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33424. * @param mesh defines the hosting mesh (can be null)
  33425. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33426. */
  33427. function CylinderGeometry(id, scene,
  33428. /**
  33429. * Defines the height of the cylinder
  33430. */
  33431. height,
  33432. /**
  33433. * Defines the diameter of the cylinder's top cap
  33434. */
  33435. diameterTop,
  33436. /**
  33437. * Defines the diameter of the cylinder's bottom cap
  33438. */
  33439. diameterBottom,
  33440. /**
  33441. * Defines the tessellation factor to apply to the cylinder
  33442. */
  33443. tessellation,
  33444. /**
  33445. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33446. */
  33447. subdivisions, canBeRegenerated, mesh,
  33448. /**
  33449. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33450. */
  33451. side) {
  33452. if (subdivisions === void 0) { subdivisions = 1; }
  33453. if (mesh === void 0) { mesh = null; }
  33454. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33455. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33456. _this.height = height;
  33457. _this.diameterTop = diameterTop;
  33458. _this.diameterBottom = diameterBottom;
  33459. _this.tessellation = tessellation;
  33460. _this.subdivisions = subdivisions;
  33461. _this.side = side;
  33462. return _this;
  33463. }
  33464. CylinderGeometry.prototype._regenerateVertexData = function () {
  33465. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33466. };
  33467. CylinderGeometry.prototype.copy = function (id) {
  33468. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33469. };
  33470. CylinderGeometry.prototype.serialize = function () {
  33471. var serializationObject = _super.prototype.serialize.call(this);
  33472. serializationObject.height = this.height;
  33473. serializationObject.diameterTop = this.diameterTop;
  33474. serializationObject.diameterBottom = this.diameterBottom;
  33475. serializationObject.tessellation = this.tessellation;
  33476. return serializationObject;
  33477. };
  33478. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  33479. if (scene.getGeometryByID(parsedCylinder.id)) {
  33480. return null; // null since geometry could be something else than a cylinder...
  33481. }
  33482. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33483. if (BABYLON.Tags) {
  33484. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33485. }
  33486. scene.pushGeometry(cylinder, true);
  33487. return cylinder;
  33488. };
  33489. return CylinderGeometry;
  33490. }(_PrimitiveGeometry));
  33491. BABYLON.CylinderGeometry = CylinderGeometry;
  33492. /**
  33493. * Creates a new torus geometry
  33494. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  33495. */
  33496. var TorusGeometry = /** @class */ (function (_super) {
  33497. __extends(TorusGeometry, _super);
  33498. /**
  33499. * Creates a new torus geometry
  33500. * @param id defines the unique ID of the geometry
  33501. * @param scene defines the hosting scene
  33502. * @param diameter defines the diameter of the torus
  33503. * @param thickness defines the thickness of the torus (ie. internal diameter)
  33504. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  33505. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33506. * @param mesh defines the hosting mesh (can be null)
  33507. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33508. */
  33509. function TorusGeometry(id, scene,
  33510. /**
  33511. * Defines the diameter of the torus
  33512. */
  33513. diameter,
  33514. /**
  33515. * Defines the thickness of the torus (ie. internal diameter)
  33516. */
  33517. thickness,
  33518. /**
  33519. * Defines the tesselation factor to apply to the torus
  33520. */
  33521. tessellation, canBeRegenerated, mesh,
  33522. /**
  33523. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33524. */
  33525. side) {
  33526. if (mesh === void 0) { mesh = null; }
  33527. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33528. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33529. _this.diameter = diameter;
  33530. _this.thickness = thickness;
  33531. _this.tessellation = tessellation;
  33532. _this.side = side;
  33533. return _this;
  33534. }
  33535. TorusGeometry.prototype._regenerateVertexData = function () {
  33536. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33537. };
  33538. TorusGeometry.prototype.copy = function (id) {
  33539. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33540. };
  33541. TorusGeometry.prototype.serialize = function () {
  33542. var serializationObject = _super.prototype.serialize.call(this);
  33543. serializationObject.diameter = this.diameter;
  33544. serializationObject.thickness = this.thickness;
  33545. serializationObject.tessellation = this.tessellation;
  33546. return serializationObject;
  33547. };
  33548. TorusGeometry.Parse = function (parsedTorus, scene) {
  33549. if (scene.getGeometryByID(parsedTorus.id)) {
  33550. return null; // null since geometry could be something else than a torus...
  33551. }
  33552. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33553. if (BABYLON.Tags) {
  33554. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33555. }
  33556. scene.pushGeometry(torus, true);
  33557. return torus;
  33558. };
  33559. return TorusGeometry;
  33560. }(_PrimitiveGeometry));
  33561. BABYLON.TorusGeometry = TorusGeometry;
  33562. /**
  33563. * Creates a new ground geometry
  33564. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  33565. */
  33566. var GroundGeometry = /** @class */ (function (_super) {
  33567. __extends(GroundGeometry, _super);
  33568. /**
  33569. * Creates a new ground geometry
  33570. * @param id defines the unique ID of the geometry
  33571. * @param scene defines the hosting scene
  33572. * @param width defines the width of the ground
  33573. * @param height defines the height of the ground
  33574. * @param subdivisions defines the subdivisions to apply to the ground
  33575. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33576. * @param mesh defines the hosting mesh (can be null)
  33577. */
  33578. function GroundGeometry(id, scene,
  33579. /**
  33580. * Defines the width of the ground
  33581. */
  33582. width,
  33583. /**
  33584. * Defines the height of the ground
  33585. */
  33586. height,
  33587. /**
  33588. * Defines the subdivisions to apply to the ground
  33589. */
  33590. subdivisions, canBeRegenerated, mesh) {
  33591. if (mesh === void 0) { mesh = null; }
  33592. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33593. _this.width = width;
  33594. _this.height = height;
  33595. _this.subdivisions = subdivisions;
  33596. return _this;
  33597. }
  33598. GroundGeometry.prototype._regenerateVertexData = function () {
  33599. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33600. };
  33601. GroundGeometry.prototype.copy = function (id) {
  33602. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33603. };
  33604. GroundGeometry.prototype.serialize = function () {
  33605. var serializationObject = _super.prototype.serialize.call(this);
  33606. serializationObject.width = this.width;
  33607. serializationObject.height = this.height;
  33608. serializationObject.subdivisions = this.subdivisions;
  33609. return serializationObject;
  33610. };
  33611. GroundGeometry.Parse = function (parsedGround, scene) {
  33612. if (scene.getGeometryByID(parsedGround.id)) {
  33613. return null; // null since geometry could be something else than a ground...
  33614. }
  33615. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33616. if (BABYLON.Tags) {
  33617. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33618. }
  33619. scene.pushGeometry(ground, true);
  33620. return ground;
  33621. };
  33622. return GroundGeometry;
  33623. }(_PrimitiveGeometry));
  33624. BABYLON.GroundGeometry = GroundGeometry;
  33625. /**
  33626. * Creates a tiled ground geometry
  33627. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  33628. */
  33629. var TiledGroundGeometry = /** @class */ (function (_super) {
  33630. __extends(TiledGroundGeometry, _super);
  33631. /**
  33632. * Creates a tiled ground geometry
  33633. * @param id defines the unique ID of the geometry
  33634. * @param scene defines the hosting scene
  33635. * @param xmin defines the minimum value on X axis
  33636. * @param zmin defines the minimum value on Z axis
  33637. * @param xmax defines the maximum value on X axis
  33638. * @param zmax defines the maximum value on Z axis
  33639. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  33640. * @param precision defines the precision to use when computing the tiles
  33641. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33642. * @param mesh defines the hosting mesh (can be null)
  33643. */
  33644. function TiledGroundGeometry(id, scene,
  33645. /**
  33646. * Defines the minimum value on X axis
  33647. */
  33648. xmin,
  33649. /**
  33650. * Defines the minimum value on Z axis
  33651. */
  33652. zmin,
  33653. /**
  33654. * Defines the maximum value on X axis
  33655. */
  33656. xmax,
  33657. /**
  33658. * Defines the maximum value on Z axis
  33659. */
  33660. zmax,
  33661. /**
  33662. * Defines the subdivisions to apply to the ground
  33663. */
  33664. subdivisions,
  33665. /**
  33666. * Defines the precision to use when computing the tiles
  33667. */
  33668. precision, canBeRegenerated, mesh) {
  33669. if (mesh === void 0) { mesh = null; }
  33670. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33671. _this.xmin = xmin;
  33672. _this.zmin = zmin;
  33673. _this.xmax = xmax;
  33674. _this.zmax = zmax;
  33675. _this.subdivisions = subdivisions;
  33676. _this.precision = precision;
  33677. return _this;
  33678. }
  33679. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  33680. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33681. };
  33682. TiledGroundGeometry.prototype.copy = function (id) {
  33683. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33684. };
  33685. return TiledGroundGeometry;
  33686. }(_PrimitiveGeometry));
  33687. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  33688. /**
  33689. * Creates a plane geometry
  33690. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  33691. */
  33692. var PlaneGeometry = /** @class */ (function (_super) {
  33693. __extends(PlaneGeometry, _super);
  33694. /**
  33695. * Creates a plane geometry
  33696. * @param id defines the unique ID of the geometry
  33697. * @param scene defines the hosting scene
  33698. * @param size defines the size of the plane (width === height)
  33699. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33700. * @param mesh defines the hosting mesh (can be null)
  33701. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33702. */
  33703. function PlaneGeometry(id, scene,
  33704. /**
  33705. * Defines the size of the plane (width === height)
  33706. */
  33707. size, canBeRegenerated, mesh,
  33708. /**
  33709. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33710. */
  33711. side) {
  33712. if (mesh === void 0) { mesh = null; }
  33713. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33714. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33715. _this.size = size;
  33716. _this.side = side;
  33717. return _this;
  33718. }
  33719. PlaneGeometry.prototype._regenerateVertexData = function () {
  33720. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33721. };
  33722. PlaneGeometry.prototype.copy = function (id) {
  33723. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33724. };
  33725. PlaneGeometry.prototype.serialize = function () {
  33726. var serializationObject = _super.prototype.serialize.call(this);
  33727. serializationObject.size = this.size;
  33728. return serializationObject;
  33729. };
  33730. PlaneGeometry.Parse = function (parsedPlane, scene) {
  33731. if (scene.getGeometryByID(parsedPlane.id)) {
  33732. return null; // null since geometry could be something else than a ground...
  33733. }
  33734. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33735. if (BABYLON.Tags) {
  33736. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33737. }
  33738. scene.pushGeometry(plane, true);
  33739. return plane;
  33740. };
  33741. return PlaneGeometry;
  33742. }(_PrimitiveGeometry));
  33743. BABYLON.PlaneGeometry = PlaneGeometry;
  33744. /**
  33745. * Creates a torus knot geometry
  33746. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  33747. */
  33748. var TorusKnotGeometry = /** @class */ (function (_super) {
  33749. __extends(TorusKnotGeometry, _super);
  33750. /**
  33751. * Creates a torus knot geometry
  33752. * @param id defines the unique ID of the geometry
  33753. * @param scene defines the hosting scene
  33754. * @param radius defines the radius of the torus knot
  33755. * @param tube defines the thickness of the torus knot tube
  33756. * @param radialSegments defines the number of radial segments
  33757. * @param tubularSegments defines the number of tubular segments
  33758. * @param p defines the first number of windings
  33759. * @param q defines the second number of windings
  33760. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33761. * @param mesh defines the hosting mesh (can be null)
  33762. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33763. */
  33764. function TorusKnotGeometry(id, scene,
  33765. /**
  33766. * Defines the radius of the torus knot
  33767. */
  33768. radius,
  33769. /**
  33770. * Defines the thickness of the torus knot tube
  33771. */
  33772. tube,
  33773. /**
  33774. * Defines the number of radial segments
  33775. */
  33776. radialSegments,
  33777. /**
  33778. * Defines the number of tubular segments
  33779. */
  33780. tubularSegments,
  33781. /**
  33782. * Defines the first number of windings
  33783. */
  33784. p,
  33785. /**
  33786. * Defines the second number of windings
  33787. */
  33788. q, canBeRegenerated, mesh,
  33789. /**
  33790. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33791. */
  33792. side) {
  33793. if (mesh === void 0) { mesh = null; }
  33794. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33795. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33796. _this.radius = radius;
  33797. _this.tube = tube;
  33798. _this.radialSegments = radialSegments;
  33799. _this.tubularSegments = tubularSegments;
  33800. _this.p = p;
  33801. _this.q = q;
  33802. _this.side = side;
  33803. return _this;
  33804. }
  33805. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  33806. 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 });
  33807. };
  33808. TorusKnotGeometry.prototype.copy = function (id) {
  33809. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  33810. };
  33811. TorusKnotGeometry.prototype.serialize = function () {
  33812. var serializationObject = _super.prototype.serialize.call(this);
  33813. serializationObject.radius = this.radius;
  33814. serializationObject.tube = this.tube;
  33815. serializationObject.radialSegments = this.radialSegments;
  33816. serializationObject.tubularSegments = this.tubularSegments;
  33817. serializationObject.p = this.p;
  33818. serializationObject.q = this.q;
  33819. return serializationObject;
  33820. };
  33821. ;
  33822. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  33823. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  33824. return null; // null since geometry could be something else than a ground...
  33825. }
  33826. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  33827. if (BABYLON.Tags) {
  33828. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  33829. }
  33830. scene.pushGeometry(torusKnot, true);
  33831. return torusKnot;
  33832. };
  33833. return TorusKnotGeometry;
  33834. }(_PrimitiveGeometry));
  33835. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  33836. //}
  33837. })(BABYLON || (BABYLON = {}));
  33838. //# sourceMappingURL=babylon.geometry.js.map
  33839. var BABYLON;
  33840. (function (BABYLON) {
  33841. var PostProcessManager = /** @class */ (function () {
  33842. function PostProcessManager(scene) {
  33843. this._vertexBuffers = {};
  33844. this._scene = scene;
  33845. }
  33846. PostProcessManager.prototype._prepareBuffers = function () {
  33847. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  33848. return;
  33849. }
  33850. // VBO
  33851. var vertices = [];
  33852. vertices.push(1, 1);
  33853. vertices.push(-1, 1);
  33854. vertices.push(-1, -1);
  33855. vertices.push(1, -1);
  33856. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  33857. this._buildIndexBuffer();
  33858. };
  33859. PostProcessManager.prototype._buildIndexBuffer = function () {
  33860. // Indices
  33861. var indices = [];
  33862. indices.push(0);
  33863. indices.push(1);
  33864. indices.push(2);
  33865. indices.push(0);
  33866. indices.push(2);
  33867. indices.push(3);
  33868. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  33869. };
  33870. PostProcessManager.prototype._rebuild = function () {
  33871. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33872. if (!vb) {
  33873. return;
  33874. }
  33875. vb._rebuild();
  33876. this._buildIndexBuffer();
  33877. };
  33878. // Methods
  33879. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  33880. if (sourceTexture === void 0) { sourceTexture = null; }
  33881. if (postProcesses === void 0) { postProcesses = null; }
  33882. var camera = this._scene.activeCamera;
  33883. if (!camera) {
  33884. return false;
  33885. }
  33886. var postProcesses = postProcesses || camera._postProcesses;
  33887. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33888. return false;
  33889. }
  33890. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  33891. return true;
  33892. };
  33893. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  33894. if (targetTexture === void 0) { targetTexture = null; }
  33895. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33896. var engine = this._scene.getEngine();
  33897. for (var index = 0; index < postProcesses.length; index++) {
  33898. if (index < postProcesses.length - 1) {
  33899. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  33900. }
  33901. else {
  33902. if (targetTexture) {
  33903. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33904. }
  33905. else {
  33906. engine.restoreDefaultFramebuffer();
  33907. }
  33908. }
  33909. var pp = postProcesses[index];
  33910. var effect = pp.apply();
  33911. if (effect) {
  33912. pp.onBeforeRenderObservable.notifyObservers(effect);
  33913. // VBOs
  33914. this._prepareBuffers();
  33915. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33916. // Draw order
  33917. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33918. pp.onAfterRenderObservable.notifyObservers(effect);
  33919. }
  33920. }
  33921. // Restore depth buffer
  33922. engine.setDepthBuffer(true);
  33923. engine.setDepthWrite(true);
  33924. };
  33925. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33926. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33927. var camera = this._scene.activeCamera;
  33928. if (!camera) {
  33929. return;
  33930. }
  33931. postProcesses = postProcesses || camera._postProcesses;
  33932. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33933. return;
  33934. }
  33935. var engine = this._scene.getEngine();
  33936. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33937. if (index < len - 1) {
  33938. postProcesses[index + 1].activate(camera, targetTexture);
  33939. }
  33940. else {
  33941. if (targetTexture) {
  33942. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33943. }
  33944. else {
  33945. engine.restoreDefaultFramebuffer();
  33946. }
  33947. }
  33948. if (doNotPresent) {
  33949. break;
  33950. }
  33951. var pp = postProcesses[index];
  33952. var effect = pp.apply();
  33953. if (effect) {
  33954. pp.onBeforeRenderObservable.notifyObservers(effect);
  33955. // VBOs
  33956. this._prepareBuffers();
  33957. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33958. // Draw order
  33959. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33960. pp.onAfterRenderObservable.notifyObservers(effect);
  33961. }
  33962. }
  33963. // Restore states
  33964. engine.setDepthBuffer(true);
  33965. engine.setDepthWrite(true);
  33966. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33967. };
  33968. PostProcessManager.prototype.dispose = function () {
  33969. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33970. if (buffer) {
  33971. buffer.dispose();
  33972. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33973. }
  33974. if (this._indexBuffer) {
  33975. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33976. this._indexBuffer = null;
  33977. }
  33978. };
  33979. return PostProcessManager;
  33980. }());
  33981. BABYLON.PostProcessManager = PostProcessManager;
  33982. })(BABYLON || (BABYLON = {}));
  33983. //# sourceMappingURL=babylon.postProcessManager.js.map
  33984. var BABYLON;
  33985. (function (BABYLON) {
  33986. /**
  33987. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33988. */
  33989. var PerformanceMonitor = /** @class */ (function () {
  33990. /**
  33991. * constructor
  33992. * @param frameSampleSize The number of samples required to saturate the sliding window
  33993. */
  33994. function PerformanceMonitor(frameSampleSize) {
  33995. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33996. this._enabled = true;
  33997. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33998. }
  33999. /**
  34000. * Samples current frame
  34001. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34002. */
  34003. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34004. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34005. if (!this._enabled)
  34006. return;
  34007. if (this._lastFrameTimeMs != null) {
  34008. var dt = timeMs - this._lastFrameTimeMs;
  34009. this._rollingFrameTime.add(dt);
  34010. }
  34011. this._lastFrameTimeMs = timeMs;
  34012. };
  34013. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34014. /**
  34015. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34016. * @return Average frame time in milliseconds
  34017. */
  34018. get: function () {
  34019. return this._rollingFrameTime.average;
  34020. },
  34021. enumerable: true,
  34022. configurable: true
  34023. });
  34024. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34025. /**
  34026. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34027. * @return Frame time variance in milliseconds squared
  34028. */
  34029. get: function () {
  34030. return this._rollingFrameTime.variance;
  34031. },
  34032. enumerable: true,
  34033. configurable: true
  34034. });
  34035. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34036. /**
  34037. * Returns the frame time of the most recent frame
  34038. * @return Frame time in milliseconds
  34039. */
  34040. get: function () {
  34041. return this._rollingFrameTime.history(0);
  34042. },
  34043. enumerable: true,
  34044. configurable: true
  34045. });
  34046. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34047. /**
  34048. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34049. * @return Framerate in frames per second
  34050. */
  34051. get: function () {
  34052. return 1000.0 / this._rollingFrameTime.average;
  34053. },
  34054. enumerable: true,
  34055. configurable: true
  34056. });
  34057. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34058. /**
  34059. * Returns the average framerate in frames per second using the most recent frame time
  34060. * @return Framerate in frames per second
  34061. */
  34062. get: function () {
  34063. var history = this._rollingFrameTime.history(0);
  34064. if (history === 0) {
  34065. return 0;
  34066. }
  34067. return 1000.0 / history;
  34068. },
  34069. enumerable: true,
  34070. configurable: true
  34071. });
  34072. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34073. /**
  34074. * Returns true if enough samples have been taken to completely fill the sliding window
  34075. * @return true if saturated
  34076. */
  34077. get: function () {
  34078. return this._rollingFrameTime.isSaturated();
  34079. },
  34080. enumerable: true,
  34081. configurable: true
  34082. });
  34083. /**
  34084. * Enables contributions to the sliding window sample set
  34085. */
  34086. PerformanceMonitor.prototype.enable = function () {
  34087. this._enabled = true;
  34088. };
  34089. /**
  34090. * Disables contributions to the sliding window sample set
  34091. * Samples will not be interpolated over the disabled period
  34092. */
  34093. PerformanceMonitor.prototype.disable = function () {
  34094. this._enabled = false;
  34095. //clear last sample to avoid interpolating over the disabled period when next enabled
  34096. this._lastFrameTimeMs = null;
  34097. };
  34098. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34099. /**
  34100. * Returns true if sampling is enabled
  34101. * @return true if enabled
  34102. */
  34103. get: function () {
  34104. return this._enabled;
  34105. },
  34106. enumerable: true,
  34107. configurable: true
  34108. });
  34109. /**
  34110. * Resets performance monitor
  34111. */
  34112. PerformanceMonitor.prototype.reset = function () {
  34113. //clear last sample to avoid interpolating over the disabled period when next enabled
  34114. this._lastFrameTimeMs = null;
  34115. //wipe record
  34116. this._rollingFrameTime.reset();
  34117. };
  34118. return PerformanceMonitor;
  34119. }());
  34120. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34121. /**
  34122. * RollingAverage
  34123. *
  34124. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34125. */
  34126. var RollingAverage = /** @class */ (function () {
  34127. /**
  34128. * constructor
  34129. * @param length The number of samples required to saturate the sliding window
  34130. */
  34131. function RollingAverage(length) {
  34132. this._samples = new Array(length);
  34133. this.reset();
  34134. }
  34135. /**
  34136. * Adds a sample to the sample set
  34137. * @param v The sample value
  34138. */
  34139. RollingAverage.prototype.add = function (v) {
  34140. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34141. var delta;
  34142. //we need to check if we've already wrapped round
  34143. if (this.isSaturated()) {
  34144. //remove bottom of stack from mean
  34145. var bottomValue = this._samples[this._pos];
  34146. delta = bottomValue - this.average;
  34147. this.average -= delta / (this._sampleCount - 1);
  34148. this._m2 -= delta * (bottomValue - this.average);
  34149. }
  34150. else {
  34151. this._sampleCount++;
  34152. }
  34153. //add new value to mean
  34154. delta = v - this.average;
  34155. this.average += delta / (this._sampleCount);
  34156. this._m2 += delta * (v - this.average);
  34157. //set the new variance
  34158. this.variance = this._m2 / (this._sampleCount - 1);
  34159. this._samples[this._pos] = v;
  34160. this._pos++;
  34161. this._pos %= this._samples.length; //positive wrap around
  34162. };
  34163. /**
  34164. * Returns previously added values or null if outside of history or outside the sliding window domain
  34165. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34166. * @return Value previously recorded with add() or null if outside of range
  34167. */
  34168. RollingAverage.prototype.history = function (i) {
  34169. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34170. return 0;
  34171. }
  34172. var i0 = this._wrapPosition(this._pos - 1.0);
  34173. return this._samples[this._wrapPosition(i0 - i)];
  34174. };
  34175. /**
  34176. * Returns true if enough samples have been taken to completely fill the sliding window
  34177. * @return true if sample-set saturated
  34178. */
  34179. RollingAverage.prototype.isSaturated = function () {
  34180. return this._sampleCount >= this._samples.length;
  34181. };
  34182. /**
  34183. * Resets the rolling average (equivalent to 0 samples taken so far)
  34184. */
  34185. RollingAverage.prototype.reset = function () {
  34186. this.average = 0;
  34187. this.variance = 0;
  34188. this._sampleCount = 0;
  34189. this._pos = 0;
  34190. this._m2 = 0;
  34191. };
  34192. /**
  34193. * Wraps a value around the sample range boundaries
  34194. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34195. * @return Wrapped position in sample range
  34196. */
  34197. RollingAverage.prototype._wrapPosition = function (i) {
  34198. var max = this._samples.length;
  34199. return ((i % max) + max) % max;
  34200. };
  34201. return RollingAverage;
  34202. }());
  34203. BABYLON.RollingAverage = RollingAverage;
  34204. })(BABYLON || (BABYLON = {}));
  34205. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34206. var BABYLON;
  34207. (function (BABYLON) {
  34208. /**
  34209. * This groups together the common properties used for image processing either in direct forward pass
  34210. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34211. * or not.
  34212. */
  34213. var ImageProcessingConfiguration = /** @class */ (function () {
  34214. function ImageProcessingConfiguration() {
  34215. /**
  34216. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34217. */
  34218. this.colorCurves = new BABYLON.ColorCurves();
  34219. this._colorCurvesEnabled = false;
  34220. this._colorGradingEnabled = false;
  34221. this._colorGradingWithGreenDepth = true;
  34222. this._colorGradingBGR = true;
  34223. this._exposure = 1.0;
  34224. this._toneMappingEnabled = false;
  34225. this._contrast = 1.0;
  34226. /**
  34227. * Vignette stretch size.
  34228. */
  34229. this.vignetteStretch = 0;
  34230. /**
  34231. * Vignette centre X Offset.
  34232. */
  34233. this.vignetteCentreX = 0;
  34234. /**
  34235. * Vignette centre Y Offset.
  34236. */
  34237. this.vignetteCentreY = 0;
  34238. /**
  34239. * Vignette weight or intensity of the vignette effect.
  34240. */
  34241. this.vignetteWeight = 1.5;
  34242. /**
  34243. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34244. * if vignetteEnabled is set to true.
  34245. */
  34246. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34247. /**
  34248. * Camera field of view used by the Vignette effect.
  34249. */
  34250. this.vignetteCameraFov = 0.5;
  34251. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34252. this._vignetteEnabled = false;
  34253. this._applyByPostProcess = false;
  34254. this._isEnabled = true;
  34255. /**
  34256. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34257. * @type {BABYLON.Observable}
  34258. */
  34259. this.onUpdateParameters = new BABYLON.Observable();
  34260. }
  34261. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34262. /**
  34263. * Gets wether the color curves effect is enabled.
  34264. */
  34265. get: function () {
  34266. return this._colorCurvesEnabled;
  34267. },
  34268. /**
  34269. * Sets wether the color curves effect is enabled.
  34270. */
  34271. set: function (value) {
  34272. if (this._colorCurvesEnabled === value) {
  34273. return;
  34274. }
  34275. this._colorCurvesEnabled = value;
  34276. this._updateParameters();
  34277. },
  34278. enumerable: true,
  34279. configurable: true
  34280. });
  34281. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34282. /**
  34283. * Gets wether the color grading effect is enabled.
  34284. */
  34285. get: function () {
  34286. return this._colorGradingEnabled;
  34287. },
  34288. /**
  34289. * Sets wether the color grading effect is enabled.
  34290. */
  34291. set: function (value) {
  34292. if (this._colorGradingEnabled === value) {
  34293. return;
  34294. }
  34295. this._colorGradingEnabled = value;
  34296. this._updateParameters();
  34297. },
  34298. enumerable: true,
  34299. configurable: true
  34300. });
  34301. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34302. /**
  34303. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34304. */
  34305. get: function () {
  34306. return this._colorGradingWithGreenDepth;
  34307. },
  34308. /**
  34309. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34310. */
  34311. set: function (value) {
  34312. if (this._colorGradingWithGreenDepth === value) {
  34313. return;
  34314. }
  34315. this._colorGradingWithGreenDepth = value;
  34316. this._updateParameters();
  34317. },
  34318. enumerable: true,
  34319. configurable: true
  34320. });
  34321. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34322. /**
  34323. * Gets wether the color grading texture contains BGR values.
  34324. */
  34325. get: function () {
  34326. return this._colorGradingBGR;
  34327. },
  34328. /**
  34329. * Sets wether the color grading texture contains BGR values.
  34330. */
  34331. set: function (value) {
  34332. if (this._colorGradingBGR === value) {
  34333. return;
  34334. }
  34335. this._colorGradingBGR = value;
  34336. this._updateParameters();
  34337. },
  34338. enumerable: true,
  34339. configurable: true
  34340. });
  34341. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34342. /**
  34343. * Gets the Exposure used in the effect.
  34344. */
  34345. get: function () {
  34346. return this._exposure;
  34347. },
  34348. /**
  34349. * Sets the Exposure used in the effect.
  34350. */
  34351. set: function (value) {
  34352. if (this._exposure === value) {
  34353. return;
  34354. }
  34355. this._exposure = value;
  34356. this._updateParameters();
  34357. },
  34358. enumerable: true,
  34359. configurable: true
  34360. });
  34361. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34362. /**
  34363. * Gets wether the tone mapping effect is enabled.
  34364. */
  34365. get: function () {
  34366. return this._toneMappingEnabled;
  34367. },
  34368. /**
  34369. * Sets wether the tone mapping effect is enabled.
  34370. */
  34371. set: function (value) {
  34372. if (this._toneMappingEnabled === value) {
  34373. return;
  34374. }
  34375. this._toneMappingEnabled = value;
  34376. this._updateParameters();
  34377. },
  34378. enumerable: true,
  34379. configurable: true
  34380. });
  34381. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34382. /**
  34383. * Gets the contrast used in the effect.
  34384. */
  34385. get: function () {
  34386. return this._contrast;
  34387. },
  34388. /**
  34389. * Sets the contrast used in the effect.
  34390. */
  34391. set: function (value) {
  34392. if (this._contrast === value) {
  34393. return;
  34394. }
  34395. this._contrast = value;
  34396. this._updateParameters();
  34397. },
  34398. enumerable: true,
  34399. configurable: true
  34400. });
  34401. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34402. /**
  34403. * Gets the vignette blend mode allowing different kind of effect.
  34404. */
  34405. get: function () {
  34406. return this._vignetteBlendMode;
  34407. },
  34408. /**
  34409. * Sets the vignette blend mode allowing different kind of effect.
  34410. */
  34411. set: function (value) {
  34412. if (this._vignetteBlendMode === value) {
  34413. return;
  34414. }
  34415. this._vignetteBlendMode = value;
  34416. this._updateParameters();
  34417. },
  34418. enumerable: true,
  34419. configurable: true
  34420. });
  34421. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34422. /**
  34423. * Gets wether the vignette effect is enabled.
  34424. */
  34425. get: function () {
  34426. return this._vignetteEnabled;
  34427. },
  34428. /**
  34429. * Sets wether the vignette effect is enabled.
  34430. */
  34431. set: function (value) {
  34432. if (this._vignetteEnabled === value) {
  34433. return;
  34434. }
  34435. this._vignetteEnabled = value;
  34436. this._updateParameters();
  34437. },
  34438. enumerable: true,
  34439. configurable: true
  34440. });
  34441. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34442. /**
  34443. * Gets wether the image processing is applied through a post process or not.
  34444. */
  34445. get: function () {
  34446. return this._applyByPostProcess;
  34447. },
  34448. /**
  34449. * Sets wether the image processing is applied through a post process or not.
  34450. */
  34451. set: function (value) {
  34452. if (this._applyByPostProcess === value) {
  34453. return;
  34454. }
  34455. this._applyByPostProcess = value;
  34456. this._updateParameters();
  34457. },
  34458. enumerable: true,
  34459. configurable: true
  34460. });
  34461. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34462. /**
  34463. * Gets wether the image processing is enabled or not.
  34464. */
  34465. get: function () {
  34466. return this._isEnabled;
  34467. },
  34468. /**
  34469. * Sets wether the image processing is enabled or not.
  34470. */
  34471. set: function (value) {
  34472. if (this._isEnabled === value) {
  34473. return;
  34474. }
  34475. this._isEnabled = value;
  34476. this._updateParameters();
  34477. },
  34478. enumerable: true,
  34479. configurable: true
  34480. });
  34481. /**
  34482. * Method called each time the image processing information changes requires to recompile the effect.
  34483. */
  34484. ImageProcessingConfiguration.prototype._updateParameters = function () {
  34485. this.onUpdateParameters.notifyObservers(this);
  34486. };
  34487. ImageProcessingConfiguration.prototype.getClassName = function () {
  34488. return "ImageProcessingConfiguration";
  34489. };
  34490. /**
  34491. * Prepare the list of uniforms associated with the Image Processing effects.
  34492. * @param uniformsList The list of uniforms used in the effect
  34493. * @param defines the list of defines currently in use
  34494. */
  34495. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  34496. if (defines.EXPOSURE) {
  34497. uniforms.push("exposureLinear");
  34498. }
  34499. if (defines.CONTRAST) {
  34500. uniforms.push("contrast");
  34501. }
  34502. if (defines.COLORGRADING) {
  34503. uniforms.push("colorTransformSettings");
  34504. }
  34505. if (defines.VIGNETTE) {
  34506. uniforms.push("vInverseScreenSize");
  34507. uniforms.push("vignetteSettings1");
  34508. uniforms.push("vignetteSettings2");
  34509. }
  34510. if (defines.COLORCURVES) {
  34511. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  34512. }
  34513. };
  34514. /**
  34515. * Prepare the list of samplers associated with the Image Processing effects.
  34516. * @param uniformsList The list of uniforms used in the effect
  34517. * @param defines the list of defines currently in use
  34518. */
  34519. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  34520. if (defines.COLORGRADING) {
  34521. samplersList.push("txColorTransform");
  34522. }
  34523. };
  34524. /**
  34525. * Prepare the list of defines associated to the shader.
  34526. * @param defines the list of defines to complete
  34527. */
  34528. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  34529. if (forPostProcess === void 0) { forPostProcess = false; }
  34530. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  34531. defines.VIGNETTE = false;
  34532. defines.TONEMAPPING = false;
  34533. defines.CONTRAST = false;
  34534. defines.EXPOSURE = false;
  34535. defines.COLORCURVES = false;
  34536. defines.COLORGRADING = false;
  34537. defines.COLORGRADING3D = false;
  34538. defines.IMAGEPROCESSING = false;
  34539. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  34540. return;
  34541. }
  34542. defines.VIGNETTE = this.vignetteEnabled;
  34543. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  34544. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  34545. defines.TONEMAPPING = this.toneMappingEnabled;
  34546. defines.CONTRAST = (this.contrast !== 1.0);
  34547. defines.EXPOSURE = (this.exposure !== 1.0);
  34548. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  34549. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  34550. if (defines.COLORGRADING) {
  34551. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  34552. }
  34553. else {
  34554. defines.COLORGRADING3D = false;
  34555. }
  34556. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  34557. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  34558. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  34559. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  34560. };
  34561. /**
  34562. * Returns true if all the image processing information are ready.
  34563. */
  34564. ImageProcessingConfiguration.prototype.isReady = function () {
  34565. // Color Grading texure can not be none blocking.
  34566. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  34567. };
  34568. /**
  34569. * Binds the image processing to the shader.
  34570. * @param effect The effect to bind to
  34571. */
  34572. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  34573. if (aspectRatio === void 0) { aspectRatio = 1; }
  34574. // Color Curves
  34575. if (this._colorCurvesEnabled && this.colorCurves) {
  34576. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  34577. }
  34578. // Vignette
  34579. if (this._vignetteEnabled) {
  34580. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  34581. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  34582. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  34583. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  34584. var vignetteScaleX = vignetteScaleY * aspectRatio;
  34585. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  34586. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  34587. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  34588. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  34589. var vignettePower = -2.0 * this.vignetteWeight;
  34590. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  34591. }
  34592. // Exposure
  34593. effect.setFloat("exposureLinear", this.exposure);
  34594. // Contrast
  34595. effect.setFloat("contrast", this.contrast);
  34596. // Color transform settings
  34597. if (this.colorGradingTexture) {
  34598. effect.setTexture("txColorTransform", this.colorGradingTexture);
  34599. var textureSize = this.colorGradingTexture.getSize().height;
  34600. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  34601. 0.5 / textureSize, // textureOffset
  34602. textureSize, // textureSize
  34603. this.colorGradingTexture.level // weight
  34604. );
  34605. }
  34606. };
  34607. /**
  34608. * Clones the current image processing instance.
  34609. * @return The cloned image processing
  34610. */
  34611. ImageProcessingConfiguration.prototype.clone = function () {
  34612. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  34613. };
  34614. /**
  34615. * Serializes the current image processing instance to a json representation.
  34616. * @return a JSON representation
  34617. */
  34618. ImageProcessingConfiguration.prototype.serialize = function () {
  34619. return BABYLON.SerializationHelper.Serialize(this);
  34620. };
  34621. /**
  34622. * Parses the image processing from a json representation.
  34623. * @param source the JSON source to parse
  34624. * @return The parsed image processing
  34625. */
  34626. ImageProcessingConfiguration.Parse = function (source) {
  34627. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  34628. };
  34629. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  34630. /**
  34631. * Used to apply the vignette as a mix with the pixel color.
  34632. */
  34633. get: function () {
  34634. return this._VIGNETTEMODE_MULTIPLY;
  34635. },
  34636. enumerable: true,
  34637. configurable: true
  34638. });
  34639. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  34640. /**
  34641. * Used to apply the vignette as a replacement of the pixel color.
  34642. */
  34643. get: function () {
  34644. return this._VIGNETTEMODE_OPAQUE;
  34645. },
  34646. enumerable: true,
  34647. configurable: true
  34648. });
  34649. // Static constants associated to the image processing.
  34650. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  34651. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  34652. __decorate([
  34653. BABYLON.serializeAsColorCurves()
  34654. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  34655. __decorate([
  34656. BABYLON.serialize()
  34657. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  34658. __decorate([
  34659. BABYLON.serializeAsTexture()
  34660. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  34661. __decorate([
  34662. BABYLON.serialize()
  34663. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  34664. __decorate([
  34665. BABYLON.serialize()
  34666. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  34667. __decorate([
  34668. BABYLON.serialize()
  34669. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  34670. __decorate([
  34671. BABYLON.serialize()
  34672. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  34673. __decorate([
  34674. BABYLON.serialize()
  34675. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  34676. __decorate([
  34677. BABYLON.serialize()
  34678. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  34679. __decorate([
  34680. BABYLON.serialize()
  34681. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  34682. __decorate([
  34683. BABYLON.serialize()
  34684. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  34685. __decorate([
  34686. BABYLON.serialize()
  34687. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  34688. __decorate([
  34689. BABYLON.serialize()
  34690. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  34691. __decorate([
  34692. BABYLON.serializeAsColor4()
  34693. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  34694. __decorate([
  34695. BABYLON.serialize()
  34696. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  34697. __decorate([
  34698. BABYLON.serialize()
  34699. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  34700. __decorate([
  34701. BABYLON.serialize()
  34702. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  34703. __decorate([
  34704. BABYLON.serialize()
  34705. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  34706. __decorate([
  34707. BABYLON.serialize()
  34708. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  34709. return ImageProcessingConfiguration;
  34710. }());
  34711. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  34712. })(BABYLON || (BABYLON = {}));
  34713. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  34714. var BABYLON;
  34715. (function (BABYLON) {
  34716. /**
  34717. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  34718. * It can help converting any input color in a desired output one. This can then be used to create effects
  34719. * from sepia, black and white to sixties or futuristic rendering...
  34720. *
  34721. * The only supported format is currently 3dl.
  34722. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  34723. */
  34724. var ColorGradingTexture = /** @class */ (function (_super) {
  34725. __extends(ColorGradingTexture, _super);
  34726. /**
  34727. * Instantiates a ColorGradingTexture from the following parameters.
  34728. *
  34729. * @param url The location of the color gradind data (currently only supporting 3dl)
  34730. * @param scene The scene the texture will be used in
  34731. */
  34732. function ColorGradingTexture(url, scene) {
  34733. var _this = _super.call(this, scene) || this;
  34734. if (!url) {
  34735. return _this;
  34736. }
  34737. _this._engine = scene.getEngine();
  34738. _this._textureMatrix = BABYLON.Matrix.Identity();
  34739. _this.name = url;
  34740. _this.url = url;
  34741. _this.hasAlpha = false;
  34742. _this.isCube = false;
  34743. _this.is3D = _this._engine.webGLVersion > 1;
  34744. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34745. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34746. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34747. _this.anisotropicFilteringLevel = 1;
  34748. _this._texture = _this._getFromCache(url, true);
  34749. if (!_this._texture) {
  34750. if (!scene.useDelayedTextureLoading) {
  34751. _this.loadTexture();
  34752. }
  34753. else {
  34754. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34755. }
  34756. }
  34757. return _this;
  34758. }
  34759. /**
  34760. * Returns the texture matrix used in most of the material.
  34761. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  34762. */
  34763. ColorGradingTexture.prototype.getTextureMatrix = function () {
  34764. return this._textureMatrix;
  34765. };
  34766. /**
  34767. * Occurs when the file being loaded is a .3dl LUT file.
  34768. */
  34769. ColorGradingTexture.prototype.load3dlTexture = function () {
  34770. var engine = this._engine;
  34771. var texture;
  34772. if (engine.webGLVersion === 1) {
  34773. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34774. }
  34775. else {
  34776. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34777. }
  34778. this._texture = texture;
  34779. var callback = function (text) {
  34780. if (typeof text !== "string") {
  34781. return;
  34782. }
  34783. var data = null;
  34784. var tempData = null;
  34785. var line;
  34786. var lines = text.split('\n');
  34787. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  34788. var maxColor = 0;
  34789. for (var i = 0; i < lines.length; i++) {
  34790. line = lines[i];
  34791. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  34792. continue;
  34793. if (line.indexOf('#') === 0)
  34794. continue;
  34795. var words = line.split(" ");
  34796. if (size === 0) {
  34797. // Number of space + one
  34798. size = words.length;
  34799. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  34800. tempData = new Float32Array(size * size * size * 4);
  34801. continue;
  34802. }
  34803. if (size != 0) {
  34804. var r = Math.max(parseInt(words[0]), 0);
  34805. var g = Math.max(parseInt(words[1]), 0);
  34806. var b = Math.max(parseInt(words[2]), 0);
  34807. maxColor = Math.max(r, maxColor);
  34808. maxColor = Math.max(g, maxColor);
  34809. maxColor = Math.max(b, maxColor);
  34810. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  34811. if (tempData) {
  34812. tempData[pixelStorageIndex + 0] = r;
  34813. tempData[pixelStorageIndex + 1] = g;
  34814. tempData[pixelStorageIndex + 2] = b;
  34815. }
  34816. pixelIndexSlice++;
  34817. if (pixelIndexSlice % size == 0) {
  34818. pixelIndexH++;
  34819. pixelIndexSlice = 0;
  34820. if (pixelIndexH % size == 0) {
  34821. pixelIndexW++;
  34822. pixelIndexH = 0;
  34823. }
  34824. }
  34825. }
  34826. }
  34827. if (tempData && data) {
  34828. for (var i = 0; i < tempData.length; i++) {
  34829. if (i > 0 && (i + 1) % 4 === 0) {
  34830. data[i] = 255;
  34831. }
  34832. else {
  34833. var value = tempData[i];
  34834. data[i] = (value / maxColor * 255);
  34835. }
  34836. }
  34837. }
  34838. if (texture.is3D) {
  34839. texture.updateSize(size, size, size);
  34840. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34841. }
  34842. else {
  34843. texture.updateSize(size * size, size);
  34844. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  34845. }
  34846. };
  34847. var scene = this.getScene();
  34848. if (scene) {
  34849. scene._loadFile(this.url, callback);
  34850. }
  34851. else {
  34852. this._engine._loadFile(this.url, callback);
  34853. }
  34854. return this._texture;
  34855. };
  34856. /**
  34857. * Starts the loading process of the texture.
  34858. */
  34859. ColorGradingTexture.prototype.loadTexture = function () {
  34860. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  34861. this.load3dlTexture();
  34862. }
  34863. };
  34864. /**
  34865. * Clones the color gradind texture.
  34866. */
  34867. ColorGradingTexture.prototype.clone = function () {
  34868. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  34869. // Base texture
  34870. newTexture.level = this.level;
  34871. return newTexture;
  34872. };
  34873. /**
  34874. * Called during delayed load for textures.
  34875. */
  34876. ColorGradingTexture.prototype.delayLoad = function () {
  34877. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  34878. return;
  34879. }
  34880. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34881. this._texture = this._getFromCache(this.url, true);
  34882. if (!this._texture) {
  34883. this.loadTexture();
  34884. }
  34885. };
  34886. /**
  34887. * Parses a color grading texture serialized by Babylon.
  34888. * @param parsedTexture The texture information being parsedTexture
  34889. * @param scene The scene to load the texture in
  34890. * @param rootUrl The root url of the data assets to load
  34891. * @return A color gradind texture
  34892. */
  34893. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  34894. var texture = null;
  34895. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  34896. texture = new ColorGradingTexture(parsedTexture.name, scene);
  34897. texture.name = parsedTexture.name;
  34898. texture.level = parsedTexture.level;
  34899. }
  34900. return texture;
  34901. };
  34902. /**
  34903. * Serializes the LUT texture to json format.
  34904. */
  34905. ColorGradingTexture.prototype.serialize = function () {
  34906. if (!this.name) {
  34907. return null;
  34908. }
  34909. var serializationObject = {};
  34910. serializationObject.name = this.name;
  34911. serializationObject.level = this.level;
  34912. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34913. return serializationObject;
  34914. };
  34915. /**
  34916. * Empty line regex stored for GC.
  34917. */
  34918. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34919. return ColorGradingTexture;
  34920. }(BABYLON.BaseTexture));
  34921. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34922. })(BABYLON || (BABYLON = {}));
  34923. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34924. var BABYLON;
  34925. (function (BABYLON) {
  34926. /**
  34927. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34928. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34929. * 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;
  34930. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34931. */
  34932. var ColorCurves = /** @class */ (function () {
  34933. function ColorCurves() {
  34934. this._dirty = true;
  34935. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34936. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34937. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34938. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34939. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34940. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34941. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34942. this._globalHue = 30;
  34943. this._globalDensity = 0;
  34944. this._globalSaturation = 0;
  34945. this._globalExposure = 0;
  34946. this._highlightsHue = 30;
  34947. this._highlightsDensity = 0;
  34948. this._highlightsSaturation = 0;
  34949. this._highlightsExposure = 0;
  34950. this._midtonesHue = 30;
  34951. this._midtonesDensity = 0;
  34952. this._midtonesSaturation = 0;
  34953. this._midtonesExposure = 0;
  34954. this._shadowsHue = 30;
  34955. this._shadowsDensity = 0;
  34956. this._shadowsSaturation = 0;
  34957. this._shadowsExposure = 0;
  34958. }
  34959. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34960. /**
  34961. * Gets the global Hue value.
  34962. * 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).
  34963. */
  34964. get: function () {
  34965. return this._globalHue;
  34966. },
  34967. /**
  34968. * Sets the global Hue value.
  34969. * 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).
  34970. */
  34971. set: function (value) {
  34972. this._globalHue = value;
  34973. this._dirty = true;
  34974. },
  34975. enumerable: true,
  34976. configurable: true
  34977. });
  34978. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34979. /**
  34980. * Gets the global Density value.
  34981. * 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.
  34982. * Values less than zero provide a filter of opposite hue.
  34983. */
  34984. get: function () {
  34985. return this._globalDensity;
  34986. },
  34987. /**
  34988. * Sets the global Density value.
  34989. * 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.
  34990. * Values less than zero provide a filter of opposite hue.
  34991. */
  34992. set: function (value) {
  34993. this._globalDensity = value;
  34994. this._dirty = true;
  34995. },
  34996. enumerable: true,
  34997. configurable: true
  34998. });
  34999. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35000. /**
  35001. * Gets the global Saturation value.
  35002. * 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.
  35003. */
  35004. get: function () {
  35005. return this._globalSaturation;
  35006. },
  35007. /**
  35008. * Sets the global Saturation value.
  35009. * 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.
  35010. */
  35011. set: function (value) {
  35012. this._globalSaturation = value;
  35013. this._dirty = true;
  35014. },
  35015. enumerable: true,
  35016. configurable: true
  35017. });
  35018. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35019. /**
  35020. * Gets the highlights Hue value.
  35021. * 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).
  35022. */
  35023. get: function () {
  35024. return this._highlightsHue;
  35025. },
  35026. /**
  35027. * Sets the highlights Hue value.
  35028. * 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).
  35029. */
  35030. set: function (value) {
  35031. this._highlightsHue = value;
  35032. this._dirty = true;
  35033. },
  35034. enumerable: true,
  35035. configurable: true
  35036. });
  35037. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35038. /**
  35039. * Gets the highlights Density value.
  35040. * 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.
  35041. * Values less than zero provide a filter of opposite hue.
  35042. */
  35043. get: function () {
  35044. return this._highlightsDensity;
  35045. },
  35046. /**
  35047. * Sets the highlights Density value.
  35048. * 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.
  35049. * Values less than zero provide a filter of opposite hue.
  35050. */
  35051. set: function (value) {
  35052. this._highlightsDensity = value;
  35053. this._dirty = true;
  35054. },
  35055. enumerable: true,
  35056. configurable: true
  35057. });
  35058. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35059. /**
  35060. * Gets the highlights Saturation value.
  35061. * 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.
  35062. */
  35063. get: function () {
  35064. return this._highlightsSaturation;
  35065. },
  35066. /**
  35067. * Sets the highlights Saturation value.
  35068. * 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.
  35069. */
  35070. set: function (value) {
  35071. this._highlightsSaturation = value;
  35072. this._dirty = true;
  35073. },
  35074. enumerable: true,
  35075. configurable: true
  35076. });
  35077. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35078. /**
  35079. * Gets the highlights Exposure value.
  35080. * 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.
  35081. */
  35082. get: function () {
  35083. return this._highlightsExposure;
  35084. },
  35085. /**
  35086. * Sets the highlights Exposure value.
  35087. * 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.
  35088. */
  35089. set: function (value) {
  35090. this._highlightsExposure = value;
  35091. this._dirty = true;
  35092. },
  35093. enumerable: true,
  35094. configurable: true
  35095. });
  35096. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35097. /**
  35098. * Gets the midtones Hue value.
  35099. * 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).
  35100. */
  35101. get: function () {
  35102. return this._midtonesHue;
  35103. },
  35104. /**
  35105. * Sets the midtones Hue value.
  35106. * 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).
  35107. */
  35108. set: function (value) {
  35109. this._midtonesHue = value;
  35110. this._dirty = true;
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35116. /**
  35117. * Gets the midtones Density value.
  35118. * 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.
  35119. * Values less than zero provide a filter of opposite hue.
  35120. */
  35121. get: function () {
  35122. return this._midtonesDensity;
  35123. },
  35124. /**
  35125. * Sets the midtones Density value.
  35126. * 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.
  35127. * Values less than zero provide a filter of opposite hue.
  35128. */
  35129. set: function (value) {
  35130. this._midtonesDensity = value;
  35131. this._dirty = true;
  35132. },
  35133. enumerable: true,
  35134. configurable: true
  35135. });
  35136. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35137. /**
  35138. * Gets the midtones Saturation value.
  35139. * 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.
  35140. */
  35141. get: function () {
  35142. return this._midtonesSaturation;
  35143. },
  35144. /**
  35145. * Sets the midtones Saturation value.
  35146. * 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.
  35147. */
  35148. set: function (value) {
  35149. this._midtonesSaturation = value;
  35150. this._dirty = true;
  35151. },
  35152. enumerable: true,
  35153. configurable: true
  35154. });
  35155. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35156. /**
  35157. * Gets the midtones Exposure value.
  35158. * 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.
  35159. */
  35160. get: function () {
  35161. return this._midtonesExposure;
  35162. },
  35163. /**
  35164. * Sets the midtones Exposure value.
  35165. * 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.
  35166. */
  35167. set: function (value) {
  35168. this._midtonesExposure = value;
  35169. this._dirty = true;
  35170. },
  35171. enumerable: true,
  35172. configurable: true
  35173. });
  35174. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35175. /**
  35176. * Gets the shadows Hue value.
  35177. * 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).
  35178. */
  35179. get: function () {
  35180. return this._shadowsHue;
  35181. },
  35182. /**
  35183. * Sets the shadows Hue value.
  35184. * 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).
  35185. */
  35186. set: function (value) {
  35187. this._shadowsHue = value;
  35188. this._dirty = true;
  35189. },
  35190. enumerable: true,
  35191. configurable: true
  35192. });
  35193. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35194. /**
  35195. * Gets the shadows Density value.
  35196. * 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.
  35197. * Values less than zero provide a filter of opposite hue.
  35198. */
  35199. get: function () {
  35200. return this._shadowsDensity;
  35201. },
  35202. /**
  35203. * Sets the shadows Density value.
  35204. * 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.
  35205. * Values less than zero provide a filter of opposite hue.
  35206. */
  35207. set: function (value) {
  35208. this._shadowsDensity = value;
  35209. this._dirty = true;
  35210. },
  35211. enumerable: true,
  35212. configurable: true
  35213. });
  35214. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35215. /**
  35216. * Gets the shadows Saturation value.
  35217. * 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.
  35218. */
  35219. get: function () {
  35220. return this._shadowsSaturation;
  35221. },
  35222. /**
  35223. * Sets the shadows Saturation value.
  35224. * 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.
  35225. */
  35226. set: function (value) {
  35227. this._shadowsSaturation = value;
  35228. this._dirty = true;
  35229. },
  35230. enumerable: true,
  35231. configurable: true
  35232. });
  35233. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35234. /**
  35235. * Gets the shadows Exposure value.
  35236. * 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.
  35237. */
  35238. get: function () {
  35239. return this._shadowsExposure;
  35240. },
  35241. /**
  35242. * Sets the shadows Exposure value.
  35243. * 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.
  35244. */
  35245. set: function (value) {
  35246. this._shadowsExposure = value;
  35247. this._dirty = true;
  35248. },
  35249. enumerable: true,
  35250. configurable: true
  35251. });
  35252. ColorCurves.prototype.getClassName = function () {
  35253. return "ColorCurves";
  35254. };
  35255. /**
  35256. * Binds the color curves to the shader.
  35257. * @param colorCurves The color curve to bind
  35258. * @param effect The effect to bind to
  35259. */
  35260. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35261. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35262. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35263. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35264. if (colorCurves._dirty) {
  35265. colorCurves._dirty = false;
  35266. // Fill in global info.
  35267. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35268. // Compute highlights info.
  35269. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35270. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35271. // Compute midtones info.
  35272. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35273. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35274. // Compute shadows info.
  35275. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35276. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35277. // Compute deltas (neutral is midtones).
  35278. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35279. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35280. }
  35281. if (effect) {
  35282. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35283. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35284. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35285. }
  35286. };
  35287. /**
  35288. * Prepare the list of uniforms associated with the ColorCurves effects.
  35289. * @param uniformsList The list of uniforms used in the effect
  35290. */
  35291. ColorCurves.PrepareUniforms = function (uniformsList) {
  35292. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35293. };
  35294. /**
  35295. * Returns color grading data based on a hue, density, saturation and exposure value.
  35296. * @param filterHue The hue of the color filter.
  35297. * @param filterDensity The density of the color filter.
  35298. * @param saturation The saturation.
  35299. * @param exposure The exposure.
  35300. * @param result The result data container.
  35301. */
  35302. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35303. if (hue == null) {
  35304. return;
  35305. }
  35306. hue = ColorCurves.clamp(hue, 0, 360);
  35307. density = ColorCurves.clamp(density, -100, 100);
  35308. saturation = ColorCurves.clamp(saturation, -100, 100);
  35309. exposure = ColorCurves.clamp(exposure, -100, 100);
  35310. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35311. // so that the maximum filter density is only 50% control. This provides fine control
  35312. // for small values and reasonable range.
  35313. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35314. density *= 0.5;
  35315. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35316. if (density < 0) {
  35317. density *= -1;
  35318. hue = (hue + 180) % 360;
  35319. }
  35320. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35321. result.scaleToRef(2, result);
  35322. result.a = 1 + 0.01 * saturation;
  35323. };
  35324. /**
  35325. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35326. * @param value The input slider value in range [-100,100].
  35327. * @returns Adjusted value.
  35328. */
  35329. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35330. value /= 100;
  35331. var x = Math.abs(value);
  35332. x = Math.pow(x, 2);
  35333. if (value < 0) {
  35334. x *= -1;
  35335. }
  35336. x *= 100;
  35337. return x;
  35338. };
  35339. /**
  35340. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35341. * @param hue The hue (H) input.
  35342. * @param saturation The saturation (S) input.
  35343. * @param brightness The brightness (B) input.
  35344. * @result An RGBA color represented as Vector4.
  35345. */
  35346. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35347. var h = ColorCurves.clamp(hue, 0, 360);
  35348. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35349. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35350. if (s === 0) {
  35351. result.r = v;
  35352. result.g = v;
  35353. result.b = v;
  35354. }
  35355. else {
  35356. // sector 0 to 5
  35357. h /= 60;
  35358. var i = Math.floor(h);
  35359. // fractional part of h
  35360. var f = h - i;
  35361. var p = v * (1 - s);
  35362. var q = v * (1 - s * f);
  35363. var t = v * (1 - s * (1 - f));
  35364. switch (i) {
  35365. case 0:
  35366. result.r = v;
  35367. result.g = t;
  35368. result.b = p;
  35369. break;
  35370. case 1:
  35371. result.r = q;
  35372. result.g = v;
  35373. result.b = p;
  35374. break;
  35375. case 2:
  35376. result.r = p;
  35377. result.g = v;
  35378. result.b = t;
  35379. break;
  35380. case 3:
  35381. result.r = p;
  35382. result.g = q;
  35383. result.b = v;
  35384. break;
  35385. case 4:
  35386. result.r = t;
  35387. result.g = p;
  35388. result.b = v;
  35389. break;
  35390. default:// case 5:
  35391. result.r = v;
  35392. result.g = p;
  35393. result.b = q;
  35394. break;
  35395. }
  35396. }
  35397. result.a = 1;
  35398. };
  35399. /**
  35400. * Returns a value clamped between min and max
  35401. * @param value The value to clamp
  35402. * @param min The minimum of value
  35403. * @param max The maximum of value
  35404. * @returns The clamped value.
  35405. */
  35406. ColorCurves.clamp = function (value, min, max) {
  35407. return Math.min(Math.max(value, min), max);
  35408. };
  35409. /**
  35410. * Clones the current color curve instance.
  35411. * @return The cloned curves
  35412. */
  35413. ColorCurves.prototype.clone = function () {
  35414. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35415. };
  35416. /**
  35417. * Serializes the current color curve instance to a json representation.
  35418. * @return a JSON representation
  35419. */
  35420. ColorCurves.prototype.serialize = function () {
  35421. return BABYLON.SerializationHelper.Serialize(this);
  35422. };
  35423. /**
  35424. * Parses the color curve from a json representation.
  35425. * @param source the JSON source to parse
  35426. * @return The parsed curves
  35427. */
  35428. ColorCurves.Parse = function (source) {
  35429. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35430. };
  35431. __decorate([
  35432. BABYLON.serialize()
  35433. ], ColorCurves.prototype, "_globalHue", void 0);
  35434. __decorate([
  35435. BABYLON.serialize()
  35436. ], ColorCurves.prototype, "_globalDensity", void 0);
  35437. __decorate([
  35438. BABYLON.serialize()
  35439. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35440. __decorate([
  35441. BABYLON.serialize()
  35442. ], ColorCurves.prototype, "_globalExposure", void 0);
  35443. __decorate([
  35444. BABYLON.serialize()
  35445. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35446. __decorate([
  35447. BABYLON.serialize()
  35448. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35449. __decorate([
  35450. BABYLON.serialize()
  35451. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35452. __decorate([
  35453. BABYLON.serialize()
  35454. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35455. __decorate([
  35456. BABYLON.serialize()
  35457. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35458. __decorate([
  35459. BABYLON.serialize()
  35460. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35461. __decorate([
  35462. BABYLON.serialize()
  35463. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35464. __decorate([
  35465. BABYLON.serialize()
  35466. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  35467. return ColorCurves;
  35468. }());
  35469. BABYLON.ColorCurves = ColorCurves;
  35470. })(BABYLON || (BABYLON = {}));
  35471. //# sourceMappingURL=babylon.colorCurves.js.map
  35472. //# sourceMappingURL=babylon.behavior.js.map
  35473. var BABYLON;
  35474. (function (BABYLON) {
  35475. var MaterialHelper = /** @class */ (function () {
  35476. function MaterialHelper() {
  35477. }
  35478. MaterialHelper.BindEyePosition = function (effect, scene) {
  35479. if (scene._forcedViewPosition) {
  35480. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35481. return;
  35482. }
  35483. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35484. };
  35485. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  35486. defines._needUVs = true;
  35487. defines[key] = true;
  35488. if (texture.getTextureMatrix().isIdentity(true)) {
  35489. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  35490. if (texture.coordinatesIndex === 0) {
  35491. defines["MAINUV1"] = true;
  35492. }
  35493. else {
  35494. defines["MAINUV2"] = true;
  35495. }
  35496. }
  35497. else {
  35498. defines[key + "DIRECTUV"] = 0;
  35499. }
  35500. };
  35501. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  35502. var matrix = texture.getTextureMatrix();
  35503. if (!matrix.isIdentity(true)) {
  35504. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  35505. }
  35506. };
  35507. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  35508. if (defines._areMiscDirty) {
  35509. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  35510. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  35511. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  35512. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  35513. }
  35514. };
  35515. /**
  35516. * Helper used to prepare the list of defines for shader compilation
  35517. * @param scene defines the current scene
  35518. * @param engine defines the current engine
  35519. * @param defines specifies the list of active defines
  35520. * @param useInstances defines if instances have to be turned on
  35521. * @param alphaTest defines if alpha testing has to be turned on
  35522. */
  35523. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  35524. var changed = false;
  35525. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  35526. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  35527. changed = true;
  35528. }
  35529. if (defines["ALPHATEST"] !== alphaTest) {
  35530. defines["ALPHATEST"] = !defines["ALPHATEST"];
  35531. changed = true;
  35532. }
  35533. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  35534. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  35535. changed = true;
  35536. }
  35537. if (defines["INSTANCES"] !== useInstances) {
  35538. defines["INSTANCES"] = useInstances;
  35539. changed = true;
  35540. }
  35541. if (changed) {
  35542. defines.markAsUnprocessed();
  35543. }
  35544. };
  35545. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  35546. if (useMorphTargets === void 0) { useMorphTargets = false; }
  35547. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  35548. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  35549. return false;
  35550. }
  35551. defines._normals = defines._needNormals;
  35552. defines._uvs = defines._needUVs;
  35553. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  35554. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35555. defines["TANGENT"] = true;
  35556. }
  35557. if (defines._needUVs) {
  35558. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  35559. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  35560. }
  35561. else {
  35562. defines["UV1"] = false;
  35563. defines["UV2"] = false;
  35564. }
  35565. if (useVertexColor) {
  35566. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  35567. defines["VERTEXCOLOR"] = hasVertexColors;
  35568. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  35569. }
  35570. if (useBones) {
  35571. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35572. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  35573. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  35574. }
  35575. else {
  35576. defines["NUM_BONE_INFLUENCERS"] = 0;
  35577. defines["BonesPerMesh"] = 0;
  35578. }
  35579. }
  35580. if (useMorphTargets) {
  35581. var manager = mesh.morphTargetManager;
  35582. if (manager) {
  35583. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  35584. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  35585. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  35586. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  35587. }
  35588. else {
  35589. defines["MORPHTARGETS_TANGENT"] = false;
  35590. defines["MORPHTARGETS_NORMAL"] = false;
  35591. defines["MORPHTARGETS"] = false;
  35592. defines["NUM_MORPH_INFLUENCERS"] = 0;
  35593. }
  35594. }
  35595. return true;
  35596. };
  35597. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  35598. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35599. if (disableLighting === void 0) { disableLighting = false; }
  35600. if (!defines._areLightsDirty) {
  35601. return defines._needNormals;
  35602. }
  35603. var lightIndex = 0;
  35604. var needNormals = false;
  35605. var needRebuild = false;
  35606. var lightmapMode = false;
  35607. var shadowEnabled = false;
  35608. var specularEnabled = false;
  35609. if (scene.lightsEnabled && !disableLighting) {
  35610. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  35611. var light = _a[_i];
  35612. needNormals = true;
  35613. if (defines["LIGHT" + lightIndex] === undefined) {
  35614. needRebuild = true;
  35615. }
  35616. defines["LIGHT" + lightIndex] = true;
  35617. defines["SPOTLIGHT" + lightIndex] = false;
  35618. defines["HEMILIGHT" + lightIndex] = false;
  35619. defines["POINTLIGHT" + lightIndex] = false;
  35620. defines["DIRLIGHT" + lightIndex] = false;
  35621. var type;
  35622. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  35623. type = "SPOTLIGHT" + lightIndex;
  35624. }
  35625. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  35626. type = "HEMILIGHT" + lightIndex;
  35627. }
  35628. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  35629. type = "POINTLIGHT" + lightIndex;
  35630. }
  35631. else {
  35632. type = "DIRLIGHT" + lightIndex;
  35633. }
  35634. defines[type] = true;
  35635. // Specular
  35636. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  35637. specularEnabled = true;
  35638. }
  35639. // Shadows
  35640. defines["SHADOW" + lightIndex] = false;
  35641. defines["SHADOWPCF" + lightIndex] = false;
  35642. defines["SHADOWESM" + lightIndex] = false;
  35643. defines["SHADOWCUBE" + lightIndex] = false;
  35644. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  35645. var shadowGenerator = light.getShadowGenerator();
  35646. if (shadowGenerator) {
  35647. shadowEnabled = true;
  35648. shadowGenerator.prepareDefines(defines, lightIndex);
  35649. }
  35650. }
  35651. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  35652. lightmapMode = true;
  35653. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  35654. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  35655. }
  35656. else {
  35657. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  35658. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  35659. }
  35660. lightIndex++;
  35661. if (lightIndex === maxSimultaneousLights)
  35662. break;
  35663. }
  35664. }
  35665. defines["SPECULARTERM"] = specularEnabled;
  35666. defines["SHADOWS"] = shadowEnabled;
  35667. // Resetting all other lights if any
  35668. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  35669. if (defines["LIGHT" + index] !== undefined) {
  35670. defines["LIGHT" + index] = false;
  35671. defines["HEMILIGHT" + lightIndex] = false;
  35672. defines["POINTLIGHT" + lightIndex] = false;
  35673. defines["DIRLIGHT" + lightIndex] = false;
  35674. defines["SPOTLIGHT" + lightIndex] = false;
  35675. defines["SHADOW" + lightIndex] = false;
  35676. }
  35677. }
  35678. var caps = scene.getEngine().getCaps();
  35679. if (defines["SHADOWFLOAT"] === undefined) {
  35680. needRebuild = true;
  35681. }
  35682. defines["SHADOWFLOAT"] = shadowEnabled &&
  35683. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  35684. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  35685. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  35686. if (needRebuild) {
  35687. defines.rebuild();
  35688. }
  35689. return needNormals;
  35690. };
  35691. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  35692. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35693. var uniformsList;
  35694. var uniformBuffersList = null;
  35695. if (uniformsListOrOptions.uniformsNames) {
  35696. var options = uniformsListOrOptions;
  35697. uniformsList = options.uniformsNames;
  35698. uniformBuffersList = options.uniformBuffersNames;
  35699. samplersList = options.samplers;
  35700. defines = options.defines;
  35701. maxSimultaneousLights = options.maxSimultaneousLights;
  35702. }
  35703. else {
  35704. uniformsList = uniformsListOrOptions;
  35705. if (!samplersList) {
  35706. samplersList = [];
  35707. }
  35708. }
  35709. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35710. if (!defines["LIGHT" + lightIndex]) {
  35711. break;
  35712. }
  35713. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  35714. if (uniformBuffersList) {
  35715. uniformBuffersList.push("Light" + lightIndex);
  35716. }
  35717. samplersList.push("shadowSampler" + lightIndex);
  35718. }
  35719. if (defines["NUM_MORPH_INFLUENCERS"]) {
  35720. uniformsList.push("morphTargetInfluences");
  35721. }
  35722. };
  35723. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  35724. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35725. if (rank === void 0) { rank = 0; }
  35726. var lightFallbackRank = 0;
  35727. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35728. if (!defines["LIGHT" + lightIndex]) {
  35729. break;
  35730. }
  35731. if (lightIndex > 0) {
  35732. lightFallbackRank = rank + lightIndex;
  35733. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  35734. }
  35735. if (!defines["SHADOWS"]) {
  35736. if (defines["SHADOW" + lightIndex]) {
  35737. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  35738. }
  35739. if (defines["SHADOWPCF" + lightIndex]) {
  35740. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  35741. }
  35742. if (defines["SHADOWESM" + lightIndex]) {
  35743. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  35744. }
  35745. }
  35746. }
  35747. return lightFallbackRank++;
  35748. };
  35749. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  35750. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  35751. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  35752. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  35753. var manager = mesh.morphTargetManager;
  35754. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  35755. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  35756. for (var index = 0; index < influencers; index++) {
  35757. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  35758. if (normal) {
  35759. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  35760. }
  35761. if (tangent) {
  35762. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  35763. }
  35764. if (attribs.length > maxAttributesCount) {
  35765. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  35766. }
  35767. }
  35768. }
  35769. };
  35770. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  35771. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  35772. fallbacks.addCPUSkinningFallback(0, mesh);
  35773. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35774. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35775. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  35776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  35778. }
  35779. }
  35780. };
  35781. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  35782. if (defines["INSTANCES"]) {
  35783. attribs.push("world0");
  35784. attribs.push("world1");
  35785. attribs.push("world2");
  35786. attribs.push("world3");
  35787. }
  35788. };
  35789. // Bindings
  35790. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  35791. if (light.shadowEnabled && mesh.receiveShadows) {
  35792. var shadowGenerator = light.getShadowGenerator();
  35793. if (shadowGenerator) {
  35794. shadowGenerator.bindShadowLight(lightIndex, effect);
  35795. }
  35796. }
  35797. };
  35798. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  35799. light.transferToEffect(effect, lightIndex + "");
  35800. };
  35801. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  35802. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35803. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  35804. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  35805. for (var i = 0; i < len; i++) {
  35806. var light = mesh._lightSources[i];
  35807. var iAsString = i.toString();
  35808. var scaledIntensity = light.getScaledIntensity();
  35809. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  35810. MaterialHelper.BindLightProperties(light, effect, i);
  35811. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  35812. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  35813. if (defines["SPECULARTERM"]) {
  35814. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  35815. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  35816. }
  35817. // Shadows
  35818. if (scene.shadowsEnabled) {
  35819. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  35820. }
  35821. light._uniformBuffer.update();
  35822. }
  35823. };
  35824. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  35825. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  35826. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  35827. effect.setColor3("vFogColor", scene.fogColor);
  35828. }
  35829. };
  35830. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  35831. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35832. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  35833. if (matrices && effect) {
  35834. effect.setMatrices("mBones", matrices);
  35835. }
  35836. }
  35837. };
  35838. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  35839. var manager = abstractMesh.morphTargetManager;
  35840. if (!abstractMesh || !manager) {
  35841. return;
  35842. }
  35843. effect.setFloatArray("morphTargetInfluences", manager.influences);
  35844. };
  35845. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  35846. if (defines["LOGARITHMICDEPTH"]) {
  35847. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  35848. }
  35849. };
  35850. MaterialHelper.BindClipPlane = function (effect, scene) {
  35851. if (scene.clipPlane) {
  35852. var clipPlane = scene.clipPlane;
  35853. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  35854. }
  35855. };
  35856. return MaterialHelper;
  35857. }());
  35858. BABYLON.MaterialHelper = MaterialHelper;
  35859. })(BABYLON || (BABYLON = {}));
  35860. //# sourceMappingURL=babylon.materialHelper.js.map
  35861. var BABYLON;
  35862. (function (BABYLON) {
  35863. var PushMaterial = /** @class */ (function (_super) {
  35864. __extends(PushMaterial, _super);
  35865. function PushMaterial(name, scene) {
  35866. var _this = _super.call(this, name, scene) || this;
  35867. _this.storeEffectOnSubMeshes = true;
  35868. return _this;
  35869. }
  35870. PushMaterial.prototype.getEffect = function () {
  35871. return this._activeEffect;
  35872. };
  35873. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  35874. if (!mesh) {
  35875. return false;
  35876. }
  35877. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  35878. return true;
  35879. }
  35880. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  35881. };
  35882. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35883. this._activeEffect.setMatrix("world", world);
  35884. };
  35885. PushMaterial.prototype.bind = function (world, mesh) {
  35886. if (!mesh) {
  35887. return;
  35888. }
  35889. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  35890. };
  35891. PushMaterial.prototype._afterBind = function (mesh, effect) {
  35892. if (effect === void 0) { effect = null; }
  35893. _super.prototype._afterBind.call(this, mesh);
  35894. this.getScene()._cachedEffect = effect;
  35895. };
  35896. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  35897. if (visibility === void 0) { visibility = 1; }
  35898. return scene.isCachedMaterialInvalid(this, effect, visibility);
  35899. };
  35900. return PushMaterial;
  35901. }(BABYLON.Material));
  35902. BABYLON.PushMaterial = PushMaterial;
  35903. })(BABYLON || (BABYLON = {}));
  35904. //# sourceMappingURL=babylon.pushMaterial.js.map
  35905. var BABYLON;
  35906. (function (BABYLON) {
  35907. var StandardMaterialDefines = /** @class */ (function (_super) {
  35908. __extends(StandardMaterialDefines, _super);
  35909. function StandardMaterialDefines() {
  35910. var _this = _super.call(this) || this;
  35911. _this.MAINUV1 = false;
  35912. _this.MAINUV2 = false;
  35913. _this.DIFFUSE = false;
  35914. _this.DIFFUSEDIRECTUV = 0;
  35915. _this.AMBIENT = false;
  35916. _this.AMBIENTDIRECTUV = 0;
  35917. _this.OPACITY = false;
  35918. _this.OPACITYDIRECTUV = 0;
  35919. _this.OPACITYRGB = false;
  35920. _this.REFLECTION = false;
  35921. _this.EMISSIVE = false;
  35922. _this.EMISSIVEDIRECTUV = 0;
  35923. _this.SPECULAR = false;
  35924. _this.SPECULARDIRECTUV = 0;
  35925. _this.BUMP = false;
  35926. _this.BUMPDIRECTUV = 0;
  35927. _this.PARALLAX = false;
  35928. _this.PARALLAXOCCLUSION = false;
  35929. _this.SPECULAROVERALPHA = false;
  35930. _this.CLIPPLANE = false;
  35931. _this.ALPHATEST = false;
  35932. _this.DEPTHPREPASS = false;
  35933. _this.ALPHAFROMDIFFUSE = false;
  35934. _this.POINTSIZE = false;
  35935. _this.FOG = false;
  35936. _this.SPECULARTERM = false;
  35937. _this.DIFFUSEFRESNEL = false;
  35938. _this.OPACITYFRESNEL = false;
  35939. _this.REFLECTIONFRESNEL = false;
  35940. _this.REFRACTIONFRESNEL = false;
  35941. _this.EMISSIVEFRESNEL = false;
  35942. _this.FRESNEL = false;
  35943. _this.NORMAL = false;
  35944. _this.UV1 = false;
  35945. _this.UV2 = false;
  35946. _this.VERTEXCOLOR = false;
  35947. _this.VERTEXALPHA = false;
  35948. _this.NUM_BONE_INFLUENCERS = 0;
  35949. _this.BonesPerMesh = 0;
  35950. _this.INSTANCES = false;
  35951. _this.GLOSSINESS = false;
  35952. _this.ROUGHNESS = false;
  35953. _this.EMISSIVEASILLUMINATION = false;
  35954. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35955. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35956. _this.LIGHTMAP = false;
  35957. _this.LIGHTMAPDIRECTUV = 0;
  35958. _this.USELIGHTMAPASSHADOWMAP = false;
  35959. _this.REFLECTIONMAP_3D = false;
  35960. _this.REFLECTIONMAP_SPHERICAL = false;
  35961. _this.REFLECTIONMAP_PLANAR = false;
  35962. _this.REFLECTIONMAP_CUBIC = false;
  35963. _this.REFLECTIONMAP_PROJECTION = false;
  35964. _this.REFLECTIONMAP_SKYBOX = false;
  35965. _this.REFLECTIONMAP_EXPLICIT = false;
  35966. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35967. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35968. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35969. _this.INVERTCUBICMAP = false;
  35970. _this.LOGARITHMICDEPTH = false;
  35971. _this.REFRACTION = false;
  35972. _this.REFRACTIONMAP_3D = false;
  35973. _this.REFLECTIONOVERALPHA = false;
  35974. _this.TWOSIDEDLIGHTING = false;
  35975. _this.SHADOWFLOAT = false;
  35976. _this.MORPHTARGETS = false;
  35977. _this.MORPHTARGETS_NORMAL = false;
  35978. _this.MORPHTARGETS_TANGENT = false;
  35979. _this.NUM_MORPH_INFLUENCERS = 0;
  35980. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35981. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35982. _this.IMAGEPROCESSING = false;
  35983. _this.VIGNETTE = false;
  35984. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35985. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35986. _this.TONEMAPPING = false;
  35987. _this.CONTRAST = false;
  35988. _this.COLORCURVES = false;
  35989. _this.COLORGRADING = false;
  35990. _this.COLORGRADING3D = false;
  35991. _this.SAMPLER3DGREENDEPTH = false;
  35992. _this.SAMPLER3DBGRMAP = false;
  35993. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35994. _this.EXPOSURE = false;
  35995. _this.rebuild();
  35996. return _this;
  35997. }
  35998. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35999. var modes = [
  36000. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36001. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36002. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36003. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36004. ];
  36005. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36006. var mode = modes_1[_i];
  36007. this[mode] = (mode === modeToEnable);
  36008. }
  36009. };
  36010. return StandardMaterialDefines;
  36011. }(BABYLON.MaterialDefines));
  36012. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36013. var StandardMaterial = /** @class */ (function (_super) {
  36014. __extends(StandardMaterial, _super);
  36015. function StandardMaterial(name, scene) {
  36016. var _this = _super.call(this, name, scene) || this;
  36017. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36018. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36019. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36020. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36021. _this.specularPower = 64;
  36022. _this._useAlphaFromDiffuseTexture = false;
  36023. _this._useEmissiveAsIllumination = false;
  36024. _this._linkEmissiveWithDiffuse = false;
  36025. _this._useSpecularOverAlpha = false;
  36026. _this._useReflectionOverAlpha = false;
  36027. _this._disableLighting = false;
  36028. _this._useParallax = false;
  36029. _this._useParallaxOcclusion = false;
  36030. _this.parallaxScaleBias = 0.05;
  36031. _this._roughness = 0;
  36032. _this.indexOfRefraction = 0.98;
  36033. _this.invertRefractionY = true;
  36034. _this._useLightmapAsShadowmap = false;
  36035. _this._useReflectionFresnelFromSpecular = false;
  36036. _this._useGlossinessFromSpecularMapAlpha = false;
  36037. _this._maxSimultaneousLights = 4;
  36038. /**
  36039. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36040. */
  36041. _this._invertNormalMapX = false;
  36042. /**
  36043. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36044. */
  36045. _this._invertNormalMapY = false;
  36046. /**
  36047. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36048. */
  36049. _this._twoSidedLighting = false;
  36050. _this._renderTargets = new BABYLON.SmartArray(16);
  36051. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36052. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36053. // Setup the default processing configuration to the scene.
  36054. _this._attachImageProcessingConfiguration(null);
  36055. _this.getRenderTargetTextures = function () {
  36056. _this._renderTargets.reset();
  36057. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36058. _this._renderTargets.push(_this._reflectionTexture);
  36059. }
  36060. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36061. _this._renderTargets.push(_this._refractionTexture);
  36062. }
  36063. return _this._renderTargets;
  36064. };
  36065. return _this;
  36066. }
  36067. ;
  36068. ;
  36069. ;
  36070. ;
  36071. ;
  36072. ;
  36073. ;
  36074. ;
  36075. ;
  36076. ;
  36077. ;
  36078. ;
  36079. ;
  36080. ;
  36081. ;
  36082. ;
  36083. ;
  36084. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36085. /**
  36086. * Gets the image processing configuration used either in this material.
  36087. */
  36088. get: function () {
  36089. return this._imageProcessingConfiguration;
  36090. },
  36091. /**
  36092. * Sets the Default image processing configuration used either in the this material.
  36093. *
  36094. * If sets to null, the scene one is in use.
  36095. */
  36096. set: function (value) {
  36097. this._attachImageProcessingConfiguration(value);
  36098. // Ensure the effect will be rebuilt.
  36099. this._markAllSubMeshesAsTexturesDirty();
  36100. },
  36101. enumerable: true,
  36102. configurable: true
  36103. });
  36104. /**
  36105. * Attaches a new image processing configuration to the Standard Material.
  36106. * @param configuration
  36107. */
  36108. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36109. var _this = this;
  36110. if (configuration === this._imageProcessingConfiguration) {
  36111. return;
  36112. }
  36113. // Detaches observer.
  36114. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36115. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36116. }
  36117. // Pick the scene configuration if needed.
  36118. if (!configuration) {
  36119. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36120. }
  36121. else {
  36122. this._imageProcessingConfiguration = configuration;
  36123. }
  36124. // Attaches observer.
  36125. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36126. _this._markAllSubMeshesAsImageProcessingDirty();
  36127. });
  36128. };
  36129. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36130. /**
  36131. * Gets wether the color curves effect is enabled.
  36132. */
  36133. get: function () {
  36134. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36135. },
  36136. /**
  36137. * Sets wether the color curves effect is enabled.
  36138. */
  36139. set: function (value) {
  36140. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36141. },
  36142. enumerable: true,
  36143. configurable: true
  36144. });
  36145. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36146. /**
  36147. * Gets wether the color grading effect is enabled.
  36148. */
  36149. get: function () {
  36150. return this.imageProcessingConfiguration.colorGradingEnabled;
  36151. },
  36152. /**
  36153. * Gets wether the color grading effect is enabled.
  36154. */
  36155. set: function (value) {
  36156. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36157. },
  36158. enumerable: true,
  36159. configurable: true
  36160. });
  36161. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36162. /**
  36163. * Gets wether tonemapping is enabled or not.
  36164. */
  36165. get: function () {
  36166. return this._imageProcessingConfiguration.toneMappingEnabled;
  36167. },
  36168. /**
  36169. * Sets wether tonemapping is enabled or not
  36170. */
  36171. set: function (value) {
  36172. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36173. },
  36174. enumerable: true,
  36175. configurable: true
  36176. });
  36177. ;
  36178. ;
  36179. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36180. /**
  36181. * The camera exposure used on this material.
  36182. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36183. * This corresponds to a photographic exposure.
  36184. */
  36185. get: function () {
  36186. return this._imageProcessingConfiguration.exposure;
  36187. },
  36188. /**
  36189. * The camera exposure used on this material.
  36190. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36191. * This corresponds to a photographic exposure.
  36192. */
  36193. set: function (value) {
  36194. this._imageProcessingConfiguration.exposure = value;
  36195. },
  36196. enumerable: true,
  36197. configurable: true
  36198. });
  36199. ;
  36200. ;
  36201. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36202. /**
  36203. * Gets The camera contrast used on this material.
  36204. */
  36205. get: function () {
  36206. return this._imageProcessingConfiguration.contrast;
  36207. },
  36208. /**
  36209. * Sets The camera contrast used on this material.
  36210. */
  36211. set: function (value) {
  36212. this._imageProcessingConfiguration.contrast = value;
  36213. },
  36214. enumerable: true,
  36215. configurable: true
  36216. });
  36217. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36218. /**
  36219. * Gets the Color Grading 2D Lookup Texture.
  36220. */
  36221. get: function () {
  36222. return this._imageProcessingConfiguration.colorGradingTexture;
  36223. },
  36224. /**
  36225. * Sets the Color Grading 2D Lookup Texture.
  36226. */
  36227. set: function (value) {
  36228. this._imageProcessingConfiguration.colorGradingTexture = value;
  36229. },
  36230. enumerable: true,
  36231. configurable: true
  36232. });
  36233. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36234. /**
  36235. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36236. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36237. * 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;
  36238. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36239. */
  36240. get: function () {
  36241. return this._imageProcessingConfiguration.colorCurves;
  36242. },
  36243. /**
  36244. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36245. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36246. * 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;
  36247. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36248. */
  36249. set: function (value) {
  36250. this._imageProcessingConfiguration.colorCurves = value;
  36251. },
  36252. enumerable: true,
  36253. configurable: true
  36254. });
  36255. StandardMaterial.prototype.getClassName = function () {
  36256. return "StandardMaterial";
  36257. };
  36258. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36259. get: function () {
  36260. return this._useLogarithmicDepth;
  36261. },
  36262. set: function (value) {
  36263. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36264. this._markAllSubMeshesAsMiscDirty();
  36265. },
  36266. enumerable: true,
  36267. configurable: true
  36268. });
  36269. StandardMaterial.prototype.needAlphaBlending = function () {
  36270. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36271. };
  36272. StandardMaterial.prototype.needAlphaTesting = function () {
  36273. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36274. };
  36275. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36276. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36277. };
  36278. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36279. return this._diffuseTexture;
  36280. };
  36281. /**
  36282. * Child classes can use it to update shaders
  36283. */
  36284. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36285. if (useInstances === void 0) { useInstances = false; }
  36286. if (subMesh.effect && this.isFrozen) {
  36287. if (this._wasPreviouslyReady && subMesh.effect) {
  36288. return true;
  36289. }
  36290. }
  36291. if (!subMesh._materialDefines) {
  36292. subMesh._materialDefines = new StandardMaterialDefines();
  36293. }
  36294. var scene = this.getScene();
  36295. var defines = subMesh._materialDefines;
  36296. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36297. if (defines._renderId === scene.getRenderId()) {
  36298. return true;
  36299. }
  36300. }
  36301. var engine = scene.getEngine();
  36302. // Lights
  36303. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36304. // Textures
  36305. if (defines._areTexturesDirty) {
  36306. defines._needUVs = false;
  36307. defines.MAINUV1 = false;
  36308. defines.MAINUV2 = false;
  36309. if (scene.texturesEnabled) {
  36310. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36311. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36312. return false;
  36313. }
  36314. else {
  36315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36316. }
  36317. }
  36318. else {
  36319. defines.DIFFUSE = false;
  36320. }
  36321. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36322. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36323. return false;
  36324. }
  36325. else {
  36326. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36327. }
  36328. }
  36329. else {
  36330. defines.AMBIENT = false;
  36331. }
  36332. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36333. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36334. return false;
  36335. }
  36336. else {
  36337. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36338. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36339. }
  36340. }
  36341. else {
  36342. defines.OPACITY = false;
  36343. }
  36344. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36345. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36346. return false;
  36347. }
  36348. else {
  36349. defines._needNormals = true;
  36350. defines.REFLECTION = true;
  36351. defines.ROUGHNESS = (this._roughness > 0);
  36352. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36353. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36354. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36355. switch (this._reflectionTexture.coordinatesMode) {
  36356. case BABYLON.Texture.CUBIC_MODE:
  36357. case BABYLON.Texture.INVCUBIC_MODE:
  36358. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36359. break;
  36360. case BABYLON.Texture.EXPLICIT_MODE:
  36361. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36362. break;
  36363. case BABYLON.Texture.PLANAR_MODE:
  36364. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36365. break;
  36366. case BABYLON.Texture.PROJECTION_MODE:
  36367. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36368. break;
  36369. case BABYLON.Texture.SKYBOX_MODE:
  36370. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36371. break;
  36372. case BABYLON.Texture.SPHERICAL_MODE:
  36373. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36374. break;
  36375. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36376. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36377. break;
  36378. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36379. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36380. break;
  36381. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36382. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36383. break;
  36384. }
  36385. }
  36386. }
  36387. else {
  36388. defines.REFLECTION = false;
  36389. }
  36390. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36391. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36392. return false;
  36393. }
  36394. else {
  36395. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36396. }
  36397. }
  36398. else {
  36399. defines.EMISSIVE = false;
  36400. }
  36401. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36402. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36403. return false;
  36404. }
  36405. else {
  36406. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36407. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36408. }
  36409. }
  36410. else {
  36411. defines.LIGHTMAP = false;
  36412. }
  36413. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36414. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36415. return false;
  36416. }
  36417. else {
  36418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36419. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36420. }
  36421. }
  36422. else {
  36423. defines.SPECULAR = false;
  36424. }
  36425. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36426. // Bump texure can not be not blocking.
  36427. if (!this._bumpTexture.isReady()) {
  36428. return false;
  36429. }
  36430. else {
  36431. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36432. defines.PARALLAX = this._useParallax;
  36433. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36434. }
  36435. }
  36436. else {
  36437. defines.BUMP = false;
  36438. }
  36439. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36440. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36441. return false;
  36442. }
  36443. else {
  36444. defines._needUVs = true;
  36445. defines.REFRACTION = true;
  36446. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36447. }
  36448. }
  36449. else {
  36450. defines.REFRACTION = false;
  36451. }
  36452. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36453. }
  36454. else {
  36455. defines.DIFFUSE = false;
  36456. defines.AMBIENT = false;
  36457. defines.OPACITY = false;
  36458. defines.REFLECTION = false;
  36459. defines.EMISSIVE = false;
  36460. defines.LIGHTMAP = false;
  36461. defines.BUMP = false;
  36462. defines.REFRACTION = false;
  36463. }
  36464. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  36465. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  36466. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  36467. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36468. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36469. }
  36470. if (defines._areImageProcessingDirty) {
  36471. if (!this._imageProcessingConfiguration.isReady()) {
  36472. return false;
  36473. }
  36474. this._imageProcessingConfiguration.prepareDefines(defines);
  36475. }
  36476. if (defines._areFresnelDirty) {
  36477. if (StandardMaterial.FresnelEnabled) {
  36478. // Fresnel
  36479. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  36480. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  36481. this._reflectionFresnelParameters) {
  36482. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  36483. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  36484. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  36485. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  36486. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  36487. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  36488. defines._needNormals = true;
  36489. defines.FRESNEL = true;
  36490. }
  36491. }
  36492. else {
  36493. defines.FRESNEL = false;
  36494. }
  36495. }
  36496. // Misc.
  36497. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36498. // Attribs
  36499. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  36500. // Values that need to be evaluated on every frame
  36501. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  36502. // Get correct effect
  36503. if (defines.isDirty) {
  36504. defines.markAsProcessed();
  36505. scene.resetCachedMaterial();
  36506. // Fallbacks
  36507. var fallbacks = new BABYLON.EffectFallbacks();
  36508. if (defines.REFLECTION) {
  36509. fallbacks.addFallback(0, "REFLECTION");
  36510. }
  36511. if (defines.SPECULAR) {
  36512. fallbacks.addFallback(0, "SPECULAR");
  36513. }
  36514. if (defines.BUMP) {
  36515. fallbacks.addFallback(0, "BUMP");
  36516. }
  36517. if (defines.PARALLAX) {
  36518. fallbacks.addFallback(1, "PARALLAX");
  36519. }
  36520. if (defines.PARALLAXOCCLUSION) {
  36521. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  36522. }
  36523. if (defines.SPECULAROVERALPHA) {
  36524. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  36525. }
  36526. if (defines.FOG) {
  36527. fallbacks.addFallback(1, "FOG");
  36528. }
  36529. if (defines.POINTSIZE) {
  36530. fallbacks.addFallback(0, "POINTSIZE");
  36531. }
  36532. if (defines.LOGARITHMICDEPTH) {
  36533. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  36534. }
  36535. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  36536. if (defines.SPECULARTERM) {
  36537. fallbacks.addFallback(0, "SPECULARTERM");
  36538. }
  36539. if (defines.DIFFUSEFRESNEL) {
  36540. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  36541. }
  36542. if (defines.OPACITYFRESNEL) {
  36543. fallbacks.addFallback(2, "OPACITYFRESNEL");
  36544. }
  36545. if (defines.REFLECTIONFRESNEL) {
  36546. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  36547. }
  36548. if (defines.EMISSIVEFRESNEL) {
  36549. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  36550. }
  36551. if (defines.FRESNEL) {
  36552. fallbacks.addFallback(4, "FRESNEL");
  36553. }
  36554. //Attributes
  36555. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36556. if (defines.NORMAL) {
  36557. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36558. }
  36559. if (defines.UV1) {
  36560. attribs.push(BABYLON.VertexBuffer.UVKind);
  36561. }
  36562. if (defines.UV2) {
  36563. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36564. }
  36565. if (defines.VERTEXCOLOR) {
  36566. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36567. }
  36568. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36569. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36570. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36571. var shaderName = "default";
  36572. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  36573. "vFogInfos", "vFogColor", "pointSize",
  36574. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36575. "mBones",
  36576. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36577. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  36578. "logarithmicDepthConstant", "vTangentSpaceParams"
  36579. ];
  36580. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  36581. var uniformBuffers = ["Material", "Scene"];
  36582. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36583. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36584. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36585. uniformsNames: uniforms,
  36586. uniformBuffersNames: uniformBuffers,
  36587. samplers: samplers,
  36588. defines: defines,
  36589. maxSimultaneousLights: this._maxSimultaneousLights
  36590. });
  36591. if (this.customShaderNameResolve) {
  36592. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  36593. }
  36594. var join = defines.toString();
  36595. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  36596. attributes: attribs,
  36597. uniformsNames: uniforms,
  36598. uniformBuffersNames: uniformBuffers,
  36599. samplers: samplers,
  36600. defines: join,
  36601. fallbacks: fallbacks,
  36602. onCompiled: this.onCompiled,
  36603. onError: this.onError,
  36604. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36605. }, engine), defines);
  36606. this.buildUniformLayout();
  36607. }
  36608. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36609. return false;
  36610. }
  36611. defines._renderId = scene.getRenderId();
  36612. this._wasPreviouslyReady = true;
  36613. return true;
  36614. };
  36615. StandardMaterial.prototype.buildUniformLayout = function () {
  36616. // Order is important !
  36617. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  36618. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  36619. this._uniformBuffer.addUniform("opacityParts", 4);
  36620. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  36621. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  36622. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  36623. this._uniformBuffer.addUniform("refractionRightColor", 4);
  36624. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  36625. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  36626. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  36627. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  36628. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36629. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36630. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36631. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36632. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  36633. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36634. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  36635. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36636. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36637. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36638. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36639. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36640. this._uniformBuffer.addUniform("specularMatrix", 16);
  36641. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36642. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36643. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36644. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36645. this._uniformBuffer.addUniform("vSpecularColor", 4);
  36646. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36647. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  36648. this._uniformBuffer.addUniform("pointSize", 1);
  36649. this._uniformBuffer.create();
  36650. };
  36651. StandardMaterial.prototype.unbind = function () {
  36652. if (this._activeEffect) {
  36653. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36654. this._activeEffect.setTexture("reflection2DSampler", null);
  36655. }
  36656. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36657. this._activeEffect.setTexture("refraction2DSampler", null);
  36658. }
  36659. }
  36660. _super.prototype.unbind.call(this);
  36661. };
  36662. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36663. var scene = this.getScene();
  36664. var defines = subMesh._materialDefines;
  36665. if (!defines) {
  36666. return;
  36667. }
  36668. var effect = subMesh.effect;
  36669. if (!effect) {
  36670. return;
  36671. }
  36672. this._activeEffect = effect;
  36673. // Matrices
  36674. this.bindOnlyWorldMatrix(world);
  36675. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36676. // Bones
  36677. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  36678. if (mustRebind) {
  36679. this._uniformBuffer.bindToEffect(effect, "Material");
  36680. this.bindViewProjection(effect);
  36681. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36682. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  36683. // Fresnel
  36684. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  36685. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  36686. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  36687. }
  36688. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  36689. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  36690. }
  36691. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  36692. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  36693. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  36694. }
  36695. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  36696. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  36697. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  36698. }
  36699. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  36700. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  36701. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  36702. }
  36703. }
  36704. // Textures
  36705. if (scene.texturesEnabled) {
  36706. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36707. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  36708. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  36709. }
  36710. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36711. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  36712. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36713. }
  36714. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36715. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36716. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36717. }
  36718. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36719. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  36720. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  36721. }
  36722. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36723. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36724. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36725. }
  36726. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36727. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36728. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36729. }
  36730. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36731. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  36732. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  36733. }
  36734. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36735. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  36736. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36737. if (scene._mirroredCameraPosition) {
  36738. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36739. }
  36740. else {
  36741. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36742. }
  36743. }
  36744. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36745. var depth = 1.0;
  36746. if (!this._refractionTexture.isCube) {
  36747. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  36748. if (this._refractionTexture.depth) {
  36749. depth = this._refractionTexture.depth;
  36750. }
  36751. }
  36752. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  36753. }
  36754. }
  36755. // Point size
  36756. if (this.pointsCloud) {
  36757. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36758. }
  36759. if (defines.SPECULARTERM) {
  36760. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  36761. }
  36762. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  36763. // Diffuse
  36764. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  36765. }
  36766. // Textures
  36767. if (scene.texturesEnabled) {
  36768. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36769. effect.setTexture("diffuseSampler", this._diffuseTexture);
  36770. }
  36771. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36772. effect.setTexture("ambientSampler", this._ambientTexture);
  36773. }
  36774. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36775. effect.setTexture("opacitySampler", this._opacityTexture);
  36776. }
  36777. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36778. if (this._reflectionTexture.isCube) {
  36779. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  36780. }
  36781. else {
  36782. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  36783. }
  36784. }
  36785. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36786. effect.setTexture("emissiveSampler", this._emissiveTexture);
  36787. }
  36788. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36789. effect.setTexture("lightmapSampler", this._lightmapTexture);
  36790. }
  36791. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36792. effect.setTexture("specularSampler", this._specularTexture);
  36793. }
  36794. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36795. effect.setTexture("bumpSampler", this._bumpTexture);
  36796. }
  36797. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36798. var depth = 1.0;
  36799. if (this._refractionTexture.isCube) {
  36800. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  36801. }
  36802. else {
  36803. effect.setTexture("refraction2DSampler", this._refractionTexture);
  36804. }
  36805. }
  36806. }
  36807. // Clip plane
  36808. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  36809. // Colors
  36810. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  36811. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  36812. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36813. }
  36814. if (mustRebind || !this.isFrozen) {
  36815. // Lights
  36816. if (scene.lightsEnabled && !this._disableLighting) {
  36817. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  36818. }
  36819. // View
  36820. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  36821. this.bindView(effect);
  36822. }
  36823. // Fog
  36824. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  36825. // Morph targets
  36826. if (defines.NUM_MORPH_INFLUENCERS) {
  36827. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  36828. }
  36829. // Log. depth
  36830. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  36831. // image processing
  36832. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  36833. this._imageProcessingConfiguration.bind(this._activeEffect);
  36834. }
  36835. }
  36836. this._uniformBuffer.update();
  36837. this._afterBind(mesh, this._activeEffect);
  36838. };
  36839. StandardMaterial.prototype.getAnimatables = function () {
  36840. var results = [];
  36841. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  36842. results.push(this._diffuseTexture);
  36843. }
  36844. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36845. results.push(this._ambientTexture);
  36846. }
  36847. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36848. results.push(this._opacityTexture);
  36849. }
  36850. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36851. results.push(this._reflectionTexture);
  36852. }
  36853. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36854. results.push(this._emissiveTexture);
  36855. }
  36856. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  36857. results.push(this._specularTexture);
  36858. }
  36859. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36860. results.push(this._bumpTexture);
  36861. }
  36862. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36863. results.push(this._lightmapTexture);
  36864. }
  36865. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36866. results.push(this._refractionTexture);
  36867. }
  36868. return results;
  36869. };
  36870. StandardMaterial.prototype.getActiveTextures = function () {
  36871. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36872. if (this._diffuseTexture) {
  36873. activeTextures.push(this._diffuseTexture);
  36874. }
  36875. if (this._ambientTexture) {
  36876. activeTextures.push(this._ambientTexture);
  36877. }
  36878. if (this._opacityTexture) {
  36879. activeTextures.push(this._opacityTexture);
  36880. }
  36881. if (this._reflectionTexture) {
  36882. activeTextures.push(this._reflectionTexture);
  36883. }
  36884. if (this._emissiveTexture) {
  36885. activeTextures.push(this._emissiveTexture);
  36886. }
  36887. if (this._specularTexture) {
  36888. activeTextures.push(this._specularTexture);
  36889. }
  36890. if (this._bumpTexture) {
  36891. activeTextures.push(this._bumpTexture);
  36892. }
  36893. if (this._lightmapTexture) {
  36894. activeTextures.push(this._lightmapTexture);
  36895. }
  36896. if (this._refractionTexture) {
  36897. activeTextures.push(this._refractionTexture);
  36898. }
  36899. return activeTextures;
  36900. };
  36901. StandardMaterial.prototype.hasTexture = function (texture) {
  36902. if (_super.prototype.hasTexture.call(this, texture)) {
  36903. return true;
  36904. }
  36905. if (this._diffuseTexture === texture) {
  36906. return true;
  36907. }
  36908. if (this._ambientTexture === texture) {
  36909. return true;
  36910. }
  36911. if (this._opacityTexture === texture) {
  36912. return true;
  36913. }
  36914. if (this._reflectionTexture === texture) {
  36915. return true;
  36916. }
  36917. if (this._emissiveTexture === texture) {
  36918. return true;
  36919. }
  36920. if (this._specularTexture === texture) {
  36921. return true;
  36922. }
  36923. if (this._bumpTexture === texture) {
  36924. return true;
  36925. }
  36926. if (this._lightmapTexture === texture) {
  36927. return true;
  36928. }
  36929. if (this._refractionTexture === texture) {
  36930. return true;
  36931. }
  36932. return false;
  36933. };
  36934. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36935. if (forceDisposeTextures) {
  36936. if (this._diffuseTexture) {
  36937. this._diffuseTexture.dispose();
  36938. }
  36939. if (this._ambientTexture) {
  36940. this._ambientTexture.dispose();
  36941. }
  36942. if (this._opacityTexture) {
  36943. this._opacityTexture.dispose();
  36944. }
  36945. if (this._reflectionTexture) {
  36946. this._reflectionTexture.dispose();
  36947. }
  36948. if (this._emissiveTexture) {
  36949. this._emissiveTexture.dispose();
  36950. }
  36951. if (this._specularTexture) {
  36952. this._specularTexture.dispose();
  36953. }
  36954. if (this._bumpTexture) {
  36955. this._bumpTexture.dispose();
  36956. }
  36957. if (this._lightmapTexture) {
  36958. this._lightmapTexture.dispose();
  36959. }
  36960. if (this._refractionTexture) {
  36961. this._refractionTexture.dispose();
  36962. }
  36963. }
  36964. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36965. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36966. }
  36967. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36968. };
  36969. StandardMaterial.prototype.clone = function (name) {
  36970. var _this = this;
  36971. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36972. result.name = name;
  36973. result.id = name;
  36974. return result;
  36975. };
  36976. StandardMaterial.prototype.serialize = function () {
  36977. return BABYLON.SerializationHelper.Serialize(this);
  36978. };
  36979. // Statics
  36980. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36981. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36982. };
  36983. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36984. get: function () {
  36985. return StandardMaterial._DiffuseTextureEnabled;
  36986. },
  36987. set: function (value) {
  36988. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36989. return;
  36990. }
  36991. StandardMaterial._DiffuseTextureEnabled = value;
  36992. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36993. },
  36994. enumerable: true,
  36995. configurable: true
  36996. });
  36997. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36998. get: function () {
  36999. return StandardMaterial._AmbientTextureEnabled;
  37000. },
  37001. set: function (value) {
  37002. if (StandardMaterial._AmbientTextureEnabled === value) {
  37003. return;
  37004. }
  37005. StandardMaterial._AmbientTextureEnabled = value;
  37006. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37007. },
  37008. enumerable: true,
  37009. configurable: true
  37010. });
  37011. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37012. get: function () {
  37013. return StandardMaterial._OpacityTextureEnabled;
  37014. },
  37015. set: function (value) {
  37016. if (StandardMaterial._OpacityTextureEnabled === value) {
  37017. return;
  37018. }
  37019. StandardMaterial._OpacityTextureEnabled = value;
  37020. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37021. },
  37022. enumerable: true,
  37023. configurable: true
  37024. });
  37025. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37026. get: function () {
  37027. return StandardMaterial._ReflectionTextureEnabled;
  37028. },
  37029. set: function (value) {
  37030. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37031. return;
  37032. }
  37033. StandardMaterial._ReflectionTextureEnabled = value;
  37034. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37035. },
  37036. enumerable: true,
  37037. configurable: true
  37038. });
  37039. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37040. get: function () {
  37041. return StandardMaterial._EmissiveTextureEnabled;
  37042. },
  37043. set: function (value) {
  37044. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37045. return;
  37046. }
  37047. StandardMaterial._EmissiveTextureEnabled = value;
  37048. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37049. },
  37050. enumerable: true,
  37051. configurable: true
  37052. });
  37053. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37054. get: function () {
  37055. return StandardMaterial._SpecularTextureEnabled;
  37056. },
  37057. set: function (value) {
  37058. if (StandardMaterial._SpecularTextureEnabled === value) {
  37059. return;
  37060. }
  37061. StandardMaterial._SpecularTextureEnabled = value;
  37062. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37063. },
  37064. enumerable: true,
  37065. configurable: true
  37066. });
  37067. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37068. get: function () {
  37069. return StandardMaterial._BumpTextureEnabled;
  37070. },
  37071. set: function (value) {
  37072. if (StandardMaterial._BumpTextureEnabled === value) {
  37073. return;
  37074. }
  37075. StandardMaterial._BumpTextureEnabled = value;
  37076. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37077. },
  37078. enumerable: true,
  37079. configurable: true
  37080. });
  37081. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37082. get: function () {
  37083. return StandardMaterial._LightmapTextureEnabled;
  37084. },
  37085. set: function (value) {
  37086. if (StandardMaterial._LightmapTextureEnabled === value) {
  37087. return;
  37088. }
  37089. StandardMaterial._LightmapTextureEnabled = value;
  37090. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37091. },
  37092. enumerable: true,
  37093. configurable: true
  37094. });
  37095. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37096. get: function () {
  37097. return StandardMaterial._RefractionTextureEnabled;
  37098. },
  37099. set: function (value) {
  37100. if (StandardMaterial._RefractionTextureEnabled === value) {
  37101. return;
  37102. }
  37103. StandardMaterial._RefractionTextureEnabled = value;
  37104. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37105. },
  37106. enumerable: true,
  37107. configurable: true
  37108. });
  37109. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37110. get: function () {
  37111. return StandardMaterial._ColorGradingTextureEnabled;
  37112. },
  37113. set: function (value) {
  37114. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37115. return;
  37116. }
  37117. StandardMaterial._ColorGradingTextureEnabled = value;
  37118. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37119. },
  37120. enumerable: true,
  37121. configurable: true
  37122. });
  37123. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37124. get: function () {
  37125. return StandardMaterial._FresnelEnabled;
  37126. },
  37127. set: function (value) {
  37128. if (StandardMaterial._FresnelEnabled === value) {
  37129. return;
  37130. }
  37131. StandardMaterial._FresnelEnabled = value;
  37132. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37133. },
  37134. enumerable: true,
  37135. configurable: true
  37136. });
  37137. // Flags used to enable or disable a type of texture for all Standard Materials
  37138. StandardMaterial._DiffuseTextureEnabled = true;
  37139. StandardMaterial._AmbientTextureEnabled = true;
  37140. StandardMaterial._OpacityTextureEnabled = true;
  37141. StandardMaterial._ReflectionTextureEnabled = true;
  37142. StandardMaterial._EmissiveTextureEnabled = true;
  37143. StandardMaterial._SpecularTextureEnabled = true;
  37144. StandardMaterial._BumpTextureEnabled = true;
  37145. StandardMaterial._LightmapTextureEnabled = true;
  37146. StandardMaterial._RefractionTextureEnabled = true;
  37147. StandardMaterial._ColorGradingTextureEnabled = true;
  37148. StandardMaterial._FresnelEnabled = true;
  37149. __decorate([
  37150. BABYLON.serializeAsTexture("diffuseTexture")
  37151. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37152. __decorate([
  37153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37154. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37155. __decorate([
  37156. BABYLON.serializeAsTexture("ambientTexture")
  37157. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37158. __decorate([
  37159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37160. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37161. __decorate([
  37162. BABYLON.serializeAsTexture("opacityTexture")
  37163. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37164. __decorate([
  37165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37166. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37167. __decorate([
  37168. BABYLON.serializeAsTexture("reflectionTexture")
  37169. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37170. __decorate([
  37171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37172. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37173. __decorate([
  37174. BABYLON.serializeAsTexture("emissiveTexture")
  37175. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37176. __decorate([
  37177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37178. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37179. __decorate([
  37180. BABYLON.serializeAsTexture("specularTexture")
  37181. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37182. __decorate([
  37183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37184. ], StandardMaterial.prototype, "specularTexture", void 0);
  37185. __decorate([
  37186. BABYLON.serializeAsTexture("bumpTexture")
  37187. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37188. __decorate([
  37189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37190. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37191. __decorate([
  37192. BABYLON.serializeAsTexture("lightmapTexture")
  37193. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37194. __decorate([
  37195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37196. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37197. __decorate([
  37198. BABYLON.serializeAsTexture("refractionTexture")
  37199. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37200. __decorate([
  37201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37202. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37203. __decorate([
  37204. BABYLON.serializeAsColor3("ambient")
  37205. ], StandardMaterial.prototype, "ambientColor", void 0);
  37206. __decorate([
  37207. BABYLON.serializeAsColor3("diffuse")
  37208. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37209. __decorate([
  37210. BABYLON.serializeAsColor3("specular")
  37211. ], StandardMaterial.prototype, "specularColor", void 0);
  37212. __decorate([
  37213. BABYLON.serializeAsColor3("emissive")
  37214. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37215. __decorate([
  37216. BABYLON.serialize()
  37217. ], StandardMaterial.prototype, "specularPower", void 0);
  37218. __decorate([
  37219. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37220. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37221. __decorate([
  37222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37223. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37224. __decorate([
  37225. BABYLON.serialize("useEmissiveAsIllumination")
  37226. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37227. __decorate([
  37228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37229. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37230. __decorate([
  37231. BABYLON.serialize("linkEmissiveWithDiffuse")
  37232. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37233. __decorate([
  37234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37235. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37236. __decorate([
  37237. BABYLON.serialize("useSpecularOverAlpha")
  37238. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37239. __decorate([
  37240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37241. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37242. __decorate([
  37243. BABYLON.serialize("useReflectionOverAlpha")
  37244. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37245. __decorate([
  37246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37247. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37248. __decorate([
  37249. BABYLON.serialize("disableLighting")
  37250. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37251. __decorate([
  37252. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37253. ], StandardMaterial.prototype, "disableLighting", void 0);
  37254. __decorate([
  37255. BABYLON.serialize("useParallax")
  37256. ], StandardMaterial.prototype, "_useParallax", void 0);
  37257. __decorate([
  37258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37259. ], StandardMaterial.prototype, "useParallax", void 0);
  37260. __decorate([
  37261. BABYLON.serialize("useParallaxOcclusion")
  37262. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37263. __decorate([
  37264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37265. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37266. __decorate([
  37267. BABYLON.serialize()
  37268. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37269. __decorate([
  37270. BABYLON.serialize("roughness")
  37271. ], StandardMaterial.prototype, "_roughness", void 0);
  37272. __decorate([
  37273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37274. ], StandardMaterial.prototype, "roughness", void 0);
  37275. __decorate([
  37276. BABYLON.serialize()
  37277. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37278. __decorate([
  37279. BABYLON.serialize()
  37280. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37281. __decorate([
  37282. BABYLON.serialize("useLightmapAsShadowmap")
  37283. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37284. __decorate([
  37285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37286. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37287. __decorate([
  37288. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37289. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37290. __decorate([
  37291. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37292. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37293. __decorate([
  37294. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37295. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37296. __decorate([
  37297. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37298. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37299. __decorate([
  37300. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37301. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37302. __decorate([
  37303. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37304. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37305. __decorate([
  37306. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37307. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37308. __decorate([
  37309. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37310. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37311. __decorate([
  37312. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37313. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37314. __decorate([
  37315. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37316. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37317. __decorate([
  37318. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37319. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37320. __decorate([
  37321. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37322. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37323. __decorate([
  37324. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37325. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37326. __decorate([
  37327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37328. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37329. __decorate([
  37330. BABYLON.serialize("maxSimultaneousLights")
  37331. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37332. __decorate([
  37333. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37334. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37335. __decorate([
  37336. BABYLON.serialize("invertNormalMapX")
  37337. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37338. __decorate([
  37339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37340. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37341. __decorate([
  37342. BABYLON.serialize("invertNormalMapY")
  37343. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37344. __decorate([
  37345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37346. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37347. __decorate([
  37348. BABYLON.serialize("twoSidedLighting")
  37349. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37350. __decorate([
  37351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37352. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37353. __decorate([
  37354. BABYLON.serialize()
  37355. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37356. return StandardMaterial;
  37357. }(BABYLON.PushMaterial));
  37358. BABYLON.StandardMaterial = StandardMaterial;
  37359. })(BABYLON || (BABYLON = {}));
  37360. //# sourceMappingURL=babylon.standardMaterial.js.map
  37361. var BABYLON;
  37362. (function (BABYLON) {
  37363. var PBRMaterialDefines = /** @class */ (function (_super) {
  37364. __extends(PBRMaterialDefines, _super);
  37365. function PBRMaterialDefines() {
  37366. var _this = _super.call(this) || this;
  37367. _this.PBR = true;
  37368. _this.MAINUV1 = false;
  37369. _this.MAINUV2 = false;
  37370. _this.UV1 = false;
  37371. _this.UV2 = false;
  37372. _this.ALBEDO = false;
  37373. _this.ALBEDODIRECTUV = 0;
  37374. _this.VERTEXCOLOR = false;
  37375. _this.AMBIENT = false;
  37376. _this.AMBIENTDIRECTUV = 0;
  37377. _this.AMBIENTINGRAYSCALE = false;
  37378. _this.OPACITY = false;
  37379. _this.VERTEXALPHA = false;
  37380. _this.OPACITYDIRECTUV = 0;
  37381. _this.OPACITYRGB = false;
  37382. _this.ALPHATEST = false;
  37383. _this.DEPTHPREPASS = false;
  37384. _this.ALPHABLEND = false;
  37385. _this.ALPHAFROMALBEDO = false;
  37386. _this.ALPHATESTVALUE = 0.5;
  37387. _this.SPECULAROVERALPHA = false;
  37388. _this.RADIANCEOVERALPHA = false;
  37389. _this.ALPHAFRESNEL = false;
  37390. _this.LINEARALPHAFRESNEL = false;
  37391. _this.PREMULTIPLYALPHA = false;
  37392. _this.EMISSIVE = false;
  37393. _this.EMISSIVEDIRECTUV = 0;
  37394. _this.REFLECTIVITY = false;
  37395. _this.REFLECTIVITYDIRECTUV = 0;
  37396. _this.SPECULARTERM = false;
  37397. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37398. _this.MICROSURFACEAUTOMATIC = false;
  37399. _this.LODBASEDMICROSFURACE = false;
  37400. _this.MICROSURFACEMAP = false;
  37401. _this.MICROSURFACEMAPDIRECTUV = 0;
  37402. _this.METALLICWORKFLOW = false;
  37403. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37404. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37405. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37406. _this.AOSTOREINMETALMAPRED = false;
  37407. _this.ENVIRONMENTBRDF = false;
  37408. _this.NORMAL = false;
  37409. _this.TANGENT = false;
  37410. _this.BUMP = false;
  37411. _this.BUMPDIRECTUV = 0;
  37412. _this.PARALLAX = false;
  37413. _this.PARALLAXOCCLUSION = false;
  37414. _this.NORMALXYSCALE = true;
  37415. _this.LIGHTMAP = false;
  37416. _this.LIGHTMAPDIRECTUV = 0;
  37417. _this.USELIGHTMAPASSHADOWMAP = false;
  37418. _this.REFLECTION = false;
  37419. _this.REFLECTIONMAP_3D = false;
  37420. _this.REFLECTIONMAP_SPHERICAL = false;
  37421. _this.REFLECTIONMAP_PLANAR = false;
  37422. _this.REFLECTIONMAP_CUBIC = false;
  37423. _this.REFLECTIONMAP_PROJECTION = false;
  37424. _this.REFLECTIONMAP_SKYBOX = false;
  37425. _this.REFLECTIONMAP_EXPLICIT = false;
  37426. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37427. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37428. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37429. _this.INVERTCUBICMAP = false;
  37430. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37431. _this.USESPHERICALINVERTEX = false;
  37432. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37433. _this.LODINREFLECTIONALPHA = false;
  37434. _this.GAMMAREFLECTION = false;
  37435. _this.RADIANCEOCCLUSION = false;
  37436. _this.HORIZONOCCLUSION = false;
  37437. _this.REFRACTION = false;
  37438. _this.REFRACTIONMAP_3D = false;
  37439. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37440. _this.LODINREFRACTIONALPHA = false;
  37441. _this.GAMMAREFRACTION = false;
  37442. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37443. _this.INSTANCES = false;
  37444. _this.NUM_BONE_INFLUENCERS = 0;
  37445. _this.BonesPerMesh = 0;
  37446. _this.NONUNIFORMSCALING = false;
  37447. _this.MORPHTARGETS = false;
  37448. _this.MORPHTARGETS_NORMAL = false;
  37449. _this.MORPHTARGETS_TANGENT = false;
  37450. _this.NUM_MORPH_INFLUENCERS = 0;
  37451. _this.IMAGEPROCESSING = false;
  37452. _this.VIGNETTE = false;
  37453. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37454. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37455. _this.TONEMAPPING = false;
  37456. _this.CONTRAST = false;
  37457. _this.COLORCURVES = false;
  37458. _this.COLORGRADING = false;
  37459. _this.COLORGRADING3D = false;
  37460. _this.SAMPLER3DGREENDEPTH = false;
  37461. _this.SAMPLER3DBGRMAP = false;
  37462. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37463. _this.EXPOSURE = false;
  37464. _this.USEPHYSICALLIGHTFALLOFF = false;
  37465. _this.TWOSIDEDLIGHTING = false;
  37466. _this.SHADOWFLOAT = false;
  37467. _this.CLIPPLANE = false;
  37468. _this.POINTSIZE = false;
  37469. _this.FOG = false;
  37470. _this.LOGARITHMICDEPTH = false;
  37471. _this.FORCENORMALFORWARD = false;
  37472. _this.rebuild();
  37473. return _this;
  37474. }
  37475. PBRMaterialDefines.prototype.reset = function () {
  37476. _super.prototype.reset.call(this);
  37477. this.ALPHATESTVALUE = 0.5;
  37478. this.PBR = true;
  37479. };
  37480. return PBRMaterialDefines;
  37481. }(BABYLON.MaterialDefines));
  37482. /**
  37483. * The Physically based material base class of BJS.
  37484. *
  37485. * This offers the main features of a standard PBR material.
  37486. * For more information, please refer to the documentation :
  37487. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37488. */
  37489. var PBRBaseMaterial = /** @class */ (function (_super) {
  37490. __extends(PBRBaseMaterial, _super);
  37491. /**
  37492. * Instantiates a new PBRMaterial instance.
  37493. *
  37494. * @param name The material name
  37495. * @param scene The scene the material will be use in.
  37496. */
  37497. function PBRBaseMaterial(name, scene) {
  37498. var _this = _super.call(this, name, scene) || this;
  37499. /**
  37500. * Intensity of the direct lights e.g. the four lights available in your scene.
  37501. * This impacts both the direct diffuse and specular highlights.
  37502. */
  37503. _this._directIntensity = 1.0;
  37504. /**
  37505. * Intensity of the emissive part of the material.
  37506. * This helps controlling the emissive effect without modifying the emissive color.
  37507. */
  37508. _this._emissiveIntensity = 1.0;
  37509. /**
  37510. * Intensity of the environment e.g. how much the environment will light the object
  37511. * either through harmonics for rough material or through the refelction for shiny ones.
  37512. */
  37513. _this._environmentIntensity = 1.0;
  37514. /**
  37515. * This is a special control allowing the reduction of the specular highlights coming from the
  37516. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37517. */
  37518. _this._specularIntensity = 1.0;
  37519. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37520. /**
  37521. * Debug Control allowing disabling the bump map on this material.
  37522. */
  37523. _this._disableBumpMap = false;
  37524. /**
  37525. * AKA Occlusion Texture Intensity in other nomenclature.
  37526. */
  37527. _this._ambientTextureStrength = 1.0;
  37528. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37529. /**
  37530. * AKA Diffuse Color in other nomenclature.
  37531. */
  37532. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37533. /**
  37534. * AKA Specular Color in other nomenclature.
  37535. */
  37536. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37537. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37538. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37539. /**
  37540. * AKA Glossiness in other nomenclature.
  37541. */
  37542. _this._microSurface = 0.9;
  37543. /**
  37544. * source material index of refraction (IOR)' / 'destination material IOR.
  37545. */
  37546. _this._indexOfRefraction = 0.66;
  37547. /**
  37548. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37549. */
  37550. _this._invertRefractionY = false;
  37551. /**
  37552. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37553. * Materials half opaque for instance using refraction could benefit from this control.
  37554. */
  37555. _this._linkRefractionWithTransparency = false;
  37556. _this._useLightmapAsShadowmap = false;
  37557. /**
  37558. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37559. * makes the reflect vector face the model (under horizon).
  37560. */
  37561. _this._useHorizonOcclusion = true;
  37562. /**
  37563. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37564. * too much the area relying on ambient texture to define their ambient occlusion.
  37565. */
  37566. _this._useRadianceOcclusion = true;
  37567. /**
  37568. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37569. */
  37570. _this._useAlphaFromAlbedoTexture = false;
  37571. /**
  37572. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37573. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37574. */
  37575. _this._useSpecularOverAlpha = true;
  37576. /**
  37577. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37578. */
  37579. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37580. /**
  37581. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37582. */
  37583. _this._useRoughnessFromMetallicTextureAlpha = true;
  37584. /**
  37585. * Specifies if the metallic texture contains the roughness information in its green channel.
  37586. */
  37587. _this._useRoughnessFromMetallicTextureGreen = false;
  37588. /**
  37589. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37590. */
  37591. _this._useMetallnessFromMetallicTextureBlue = false;
  37592. /**
  37593. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37594. */
  37595. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37596. /**
  37597. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37598. */
  37599. _this._useAmbientInGrayScale = false;
  37600. /**
  37601. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37602. * The material will try to infer what glossiness each pixel should be.
  37603. */
  37604. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37605. /**
  37606. * BJS is using an harcoded light falloff based on a manually sets up range.
  37607. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37608. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37609. */
  37610. _this._usePhysicalLightFalloff = true;
  37611. /**
  37612. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37613. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37614. */
  37615. _this._useRadianceOverAlpha = true;
  37616. /**
  37617. * Allows using the bump map in parallax mode.
  37618. */
  37619. _this._useParallax = false;
  37620. /**
  37621. * Allows using the bump map in parallax occlusion mode.
  37622. */
  37623. _this._useParallaxOcclusion = false;
  37624. /**
  37625. * Controls the scale bias of the parallax mode.
  37626. */
  37627. _this._parallaxScaleBias = 0.05;
  37628. /**
  37629. * If sets to true, disables all the lights affecting the material.
  37630. */
  37631. _this._disableLighting = false;
  37632. /**
  37633. * Number of Simultaneous lights allowed on the material.
  37634. */
  37635. _this._maxSimultaneousLights = 4;
  37636. /**
  37637. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37638. */
  37639. _this._invertNormalMapX = false;
  37640. /**
  37641. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37642. */
  37643. _this._invertNormalMapY = false;
  37644. /**
  37645. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37646. */
  37647. _this._twoSidedLighting = false;
  37648. /**
  37649. * Defines the alpha limits in alpha test mode.
  37650. */
  37651. _this._alphaCutOff = 0.4;
  37652. /**
  37653. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37654. */
  37655. _this._forceAlphaTest = false;
  37656. /**
  37657. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37658. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37659. */
  37660. _this._useAlphaFresnel = false;
  37661. /**
  37662. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37663. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37664. */
  37665. _this._useLinearAlphaFresnel = false;
  37666. /**
  37667. * The transparency mode of the material.
  37668. */
  37669. _this._transparencyMode = null;
  37670. /**
  37671. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37672. * from cos thetav and roughness:
  37673. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37674. */
  37675. _this._environmentBRDFTexture = null;
  37676. /**
  37677. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37678. */
  37679. _this._forceIrradianceInFragment = false;
  37680. /**
  37681. * Force normal to face away from face.
  37682. */
  37683. _this._forceNormalForward = false;
  37684. /**
  37685. * Force metallic workflow.
  37686. */
  37687. _this._forceMetallicWorkflow = false;
  37688. _this._renderTargets = new BABYLON.SmartArray(16);
  37689. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37690. // Setup the default processing configuration to the scene.
  37691. _this._attachImageProcessingConfiguration(null);
  37692. _this.getRenderTargetTextures = function () {
  37693. _this._renderTargets.reset();
  37694. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37695. _this._renderTargets.push(_this._reflectionTexture);
  37696. }
  37697. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37698. _this._renderTargets.push(_this._refractionTexture);
  37699. }
  37700. return _this._renderTargets;
  37701. };
  37702. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37703. return _this;
  37704. }
  37705. /**
  37706. * Attaches a new image processing configuration to the PBR Material.
  37707. * @param configuration
  37708. */
  37709. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37710. var _this = this;
  37711. if (configuration === this._imageProcessingConfiguration) {
  37712. return;
  37713. }
  37714. // Detaches observer.
  37715. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37716. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37717. }
  37718. // Pick the scene configuration if needed.
  37719. if (!configuration) {
  37720. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37721. }
  37722. else {
  37723. this._imageProcessingConfiguration = configuration;
  37724. }
  37725. // Attaches observer.
  37726. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37727. _this._markAllSubMeshesAsImageProcessingDirty();
  37728. });
  37729. };
  37730. PBRBaseMaterial.prototype.getClassName = function () {
  37731. return "PBRBaseMaterial";
  37732. };
  37733. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37734. get: function () {
  37735. return this._useLogarithmicDepth;
  37736. },
  37737. set: function (value) {
  37738. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37739. },
  37740. enumerable: true,
  37741. configurable: true
  37742. });
  37743. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  37744. /**
  37745. * Gets the current transparency mode.
  37746. */
  37747. get: function () {
  37748. return this._transparencyMode;
  37749. },
  37750. /**
  37751. * Sets the transparency mode of the material.
  37752. */
  37753. set: function (value) {
  37754. if (this._transparencyMode === value) {
  37755. return;
  37756. }
  37757. this._transparencyMode = value;
  37758. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  37759. this._markAllSubMeshesAsTexturesDirty();
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  37765. /**
  37766. * Returns true if alpha blending should be disabled.
  37767. */
  37768. get: function () {
  37769. return (this._linkRefractionWithTransparency ||
  37770. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  37771. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37772. },
  37773. enumerable: true,
  37774. configurable: true
  37775. });
  37776. /**
  37777. * Specifies whether or not this material should be rendered in alpha blend mode.
  37778. */
  37779. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  37780. if (this._disableAlphaBlending) {
  37781. return false;
  37782. }
  37783. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  37784. };
  37785. /**
  37786. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  37787. */
  37788. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  37789. if (this._disableAlphaBlending) {
  37790. return false;
  37791. }
  37792. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  37793. };
  37794. /**
  37795. * Specifies whether or not this material should be rendered in alpha test mode.
  37796. */
  37797. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  37798. if (this._forceAlphaTest) {
  37799. return true;
  37800. }
  37801. if (this._linkRefractionWithTransparency) {
  37802. return false;
  37803. }
  37804. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  37805. };
  37806. /**
  37807. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  37808. */
  37809. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  37810. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  37811. };
  37812. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  37813. return this._albedoTexture;
  37814. };
  37815. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  37816. var _this = this;
  37817. if (subMesh.effect && this.isFrozen) {
  37818. if (this._wasPreviouslyReady) {
  37819. return true;
  37820. }
  37821. }
  37822. if (!subMesh._materialDefines) {
  37823. subMesh._materialDefines = new PBRMaterialDefines();
  37824. }
  37825. var scene = this.getScene();
  37826. var defines = subMesh._materialDefines;
  37827. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  37828. if (defines._renderId === scene.getRenderId()) {
  37829. return true;
  37830. }
  37831. }
  37832. var engine = scene.getEngine();
  37833. // Lights
  37834. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  37835. defines._needNormals = true;
  37836. // Textures
  37837. if (defines._areTexturesDirty) {
  37838. defines._needUVs = false;
  37839. if (scene.texturesEnabled) {
  37840. if (scene.getEngine().getCaps().textureLOD) {
  37841. defines.LODBASEDMICROSFURACE = true;
  37842. }
  37843. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37844. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  37845. return false;
  37846. }
  37847. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  37848. }
  37849. else {
  37850. defines.ALBEDO = false;
  37851. }
  37852. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37853. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  37854. return false;
  37855. }
  37856. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  37857. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  37858. }
  37859. else {
  37860. defines.AMBIENT = false;
  37861. }
  37862. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37863. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  37864. return false;
  37865. }
  37866. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  37867. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  37868. }
  37869. else {
  37870. defines.OPACITY = false;
  37871. }
  37872. var reflectionTexture = this._getReflectionTexture();
  37873. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37874. if (!reflectionTexture.isReadyOrNotBlocking()) {
  37875. return false;
  37876. }
  37877. defines.REFLECTION = true;
  37878. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  37879. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  37880. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  37881. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  37882. defines.INVERTCUBICMAP = true;
  37883. }
  37884. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  37885. switch (reflectionTexture.coordinatesMode) {
  37886. case BABYLON.Texture.CUBIC_MODE:
  37887. case BABYLON.Texture.INVCUBIC_MODE:
  37888. defines.REFLECTIONMAP_CUBIC = true;
  37889. break;
  37890. case BABYLON.Texture.EXPLICIT_MODE:
  37891. defines.REFLECTIONMAP_EXPLICIT = true;
  37892. break;
  37893. case BABYLON.Texture.PLANAR_MODE:
  37894. defines.REFLECTIONMAP_PLANAR = true;
  37895. break;
  37896. case BABYLON.Texture.PROJECTION_MODE:
  37897. defines.REFLECTIONMAP_PROJECTION = true;
  37898. break;
  37899. case BABYLON.Texture.SKYBOX_MODE:
  37900. defines.REFLECTIONMAP_SKYBOX = true;
  37901. break;
  37902. case BABYLON.Texture.SPHERICAL_MODE:
  37903. defines.REFLECTIONMAP_SPHERICAL = true;
  37904. break;
  37905. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37906. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37907. break;
  37908. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37909. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37910. break;
  37911. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37912. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37913. break;
  37914. }
  37915. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37916. if (reflectionTexture.sphericalPolynomial) {
  37917. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37918. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37919. defines.USESPHERICALINVERTEX = false;
  37920. }
  37921. else {
  37922. defines.USESPHERICALINVERTEX = true;
  37923. }
  37924. }
  37925. }
  37926. }
  37927. else {
  37928. defines.REFLECTION = false;
  37929. defines.REFLECTIONMAP_3D = false;
  37930. defines.REFLECTIONMAP_SPHERICAL = false;
  37931. defines.REFLECTIONMAP_PLANAR = false;
  37932. defines.REFLECTIONMAP_CUBIC = false;
  37933. defines.REFLECTIONMAP_PROJECTION = false;
  37934. defines.REFLECTIONMAP_SKYBOX = false;
  37935. defines.REFLECTIONMAP_EXPLICIT = false;
  37936. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37937. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37938. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37939. defines.INVERTCUBICMAP = false;
  37940. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37941. defines.USESPHERICALINVERTEX = false;
  37942. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37943. defines.LODINREFLECTIONALPHA = false;
  37944. defines.GAMMAREFLECTION = false;
  37945. }
  37946. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37947. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37948. return false;
  37949. }
  37950. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37951. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37952. }
  37953. else {
  37954. defines.LIGHTMAP = false;
  37955. }
  37956. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37957. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37958. return false;
  37959. }
  37960. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37961. }
  37962. else {
  37963. defines.EMISSIVE = false;
  37964. }
  37965. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37966. if (this._metallicTexture) {
  37967. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37968. return false;
  37969. }
  37970. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37971. defines.METALLICWORKFLOW = true;
  37972. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37973. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37974. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37975. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37976. }
  37977. else if (this._reflectivityTexture) {
  37978. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37979. return false;
  37980. }
  37981. defines.METALLICWORKFLOW = false;
  37982. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37983. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37984. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37985. }
  37986. else {
  37987. defines.METALLICWORKFLOW = false;
  37988. defines.REFLECTIVITY = false;
  37989. }
  37990. if (this._microSurfaceTexture) {
  37991. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37992. return false;
  37993. }
  37994. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37995. }
  37996. else {
  37997. defines.MICROSURFACEMAP = false;
  37998. }
  37999. }
  38000. else {
  38001. defines.REFLECTIVITY = false;
  38002. defines.MICROSURFACEMAP = false;
  38003. }
  38004. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38005. // Bump texure can not be none blocking.
  38006. if (!this._bumpTexture.isReady()) {
  38007. return false;
  38008. }
  38009. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38010. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38011. defines.PARALLAX = true;
  38012. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38013. }
  38014. else {
  38015. defines.PARALLAX = false;
  38016. }
  38017. }
  38018. else {
  38019. defines.BUMP = false;
  38020. }
  38021. var refractionTexture = this._getRefractionTexture();
  38022. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38023. if (!refractionTexture.isReadyOrNotBlocking()) {
  38024. return false;
  38025. }
  38026. defines.REFRACTION = true;
  38027. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38028. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38029. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38030. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38031. if (this._linkRefractionWithTransparency) {
  38032. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38033. }
  38034. }
  38035. else {
  38036. defines.REFRACTION = false;
  38037. }
  38038. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38039. // This is blocking.
  38040. if (!this._environmentBRDFTexture.isReady()) {
  38041. return false;
  38042. }
  38043. defines.ENVIRONMENTBRDF = true;
  38044. }
  38045. else {
  38046. defines.ENVIRONMENTBRDF = false;
  38047. }
  38048. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38049. defines.ALPHAFROMALBEDO = true;
  38050. }
  38051. else {
  38052. defines.ALPHAFROMALBEDO = false;
  38053. }
  38054. }
  38055. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38056. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38057. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38058. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38059. defines.METALLICWORKFLOW = true;
  38060. }
  38061. else {
  38062. defines.METALLICWORKFLOW = false;
  38063. }
  38064. if (!this.backFaceCulling && this._twoSidedLighting) {
  38065. defines.TWOSIDEDLIGHTING = true;
  38066. }
  38067. else {
  38068. defines.TWOSIDEDLIGHTING = false;
  38069. }
  38070. defines.ALPHATESTVALUE = this._alphaCutOff;
  38071. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38072. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38073. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38074. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38075. }
  38076. if (defines._areImageProcessingDirty) {
  38077. if (!this._imageProcessingConfiguration.isReady()) {
  38078. return false;
  38079. }
  38080. this._imageProcessingConfiguration.prepareDefines(defines);
  38081. }
  38082. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38083. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38084. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38085. // Misc.
  38086. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  38087. // Values that need to be evaluated on every frame
  38088. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  38089. // Attribs
  38090. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38091. var bufferMesh = null;
  38092. if (mesh instanceof BABYLON.InstancedMesh) {
  38093. bufferMesh = mesh.sourceMesh;
  38094. }
  38095. else if (mesh instanceof BABYLON.Mesh) {
  38096. bufferMesh = mesh;
  38097. }
  38098. if (bufferMesh) {
  38099. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38100. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38101. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38102. var normals = normalVertexBuffer.getData();
  38103. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38104. var strideSize = normalVertexBuffer.getStrideSize();
  38105. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38106. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38107. defines.NORMAL = false;
  38108. }
  38109. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38110. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38111. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38112. var tangents = tangentVertexBuffer.getData();
  38113. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38114. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38115. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38116. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38117. defines.TANGENT = false;
  38118. }
  38119. }
  38120. }
  38121. else {
  38122. if (!scene.getEngine().getCaps().standardDerivatives) {
  38123. bufferMesh.createNormals(true);
  38124. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38125. }
  38126. }
  38127. }
  38128. }
  38129. // Get correct effect
  38130. if (defines.isDirty) {
  38131. defines.markAsProcessed();
  38132. scene.resetCachedMaterial();
  38133. // Fallbacks
  38134. var fallbacks = new BABYLON.EffectFallbacks();
  38135. var fallbackRank = 0;
  38136. if (defines.USESPHERICALINVERTEX) {
  38137. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38138. }
  38139. if (defines.FOG) {
  38140. fallbacks.addFallback(fallbackRank, "FOG");
  38141. }
  38142. if (defines.POINTSIZE) {
  38143. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38144. }
  38145. if (defines.LOGARITHMICDEPTH) {
  38146. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38147. }
  38148. if (defines.PARALLAX) {
  38149. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38150. }
  38151. if (defines.PARALLAXOCCLUSION) {
  38152. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38153. }
  38154. if (defines.ENVIRONMENTBRDF) {
  38155. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38156. }
  38157. if (defines.TANGENT) {
  38158. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38159. }
  38160. if (defines.BUMP) {
  38161. fallbacks.addFallback(fallbackRank++, "BUMP");
  38162. }
  38163. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38164. if (defines.SPECULARTERM) {
  38165. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38166. }
  38167. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38168. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38169. }
  38170. if (defines.LIGHTMAP) {
  38171. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38172. }
  38173. if (defines.NORMAL) {
  38174. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38175. }
  38176. if (defines.AMBIENT) {
  38177. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38178. }
  38179. if (defines.EMISSIVE) {
  38180. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38181. }
  38182. if (defines.VERTEXCOLOR) {
  38183. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38184. }
  38185. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38186. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38187. }
  38188. if (defines.MORPHTARGETS) {
  38189. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38190. }
  38191. //Attributes
  38192. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38193. if (defines.NORMAL) {
  38194. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38195. }
  38196. if (defines.TANGENT) {
  38197. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38198. }
  38199. if (defines.UV1) {
  38200. attribs.push(BABYLON.VertexBuffer.UVKind);
  38201. }
  38202. if (defines.UV2) {
  38203. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38204. }
  38205. if (defines.VERTEXCOLOR) {
  38206. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38207. }
  38208. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38209. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38210. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38211. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38212. "vFogInfos", "vFogColor", "pointSize",
  38213. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38214. "mBones",
  38215. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38216. "vLightingIntensity",
  38217. "logarithmicDepthConstant",
  38218. "vSphericalX", "vSphericalY", "vSphericalZ",
  38219. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38220. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38221. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38222. "vTangentSpaceParams"
  38223. ];
  38224. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38225. "bumpSampler", "lightmapSampler", "opacitySampler",
  38226. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38227. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38228. "microSurfaceSampler", "environmentBrdfSampler"];
  38229. var uniformBuffers = ["Material", "Scene"];
  38230. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38231. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38232. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38233. uniformsNames: uniforms,
  38234. uniformBuffersNames: uniformBuffers,
  38235. samplers: samplers,
  38236. defines: defines,
  38237. maxSimultaneousLights: this._maxSimultaneousLights
  38238. });
  38239. var onCompiled = function (effect) {
  38240. if (_this.onCompiled) {
  38241. _this.onCompiled(effect);
  38242. }
  38243. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38244. };
  38245. var join = defines.toString();
  38246. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38247. attributes: attribs,
  38248. uniformsNames: uniforms,
  38249. uniformBuffersNames: uniformBuffers,
  38250. samplers: samplers,
  38251. defines: join,
  38252. fallbacks: fallbacks,
  38253. onCompiled: onCompiled,
  38254. onError: this.onError,
  38255. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38256. }, engine), defines);
  38257. this.buildUniformLayout();
  38258. }
  38259. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38260. return false;
  38261. }
  38262. defines._renderId = scene.getRenderId();
  38263. this._wasPreviouslyReady = true;
  38264. return true;
  38265. };
  38266. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38267. // Order is important !
  38268. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38269. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38270. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38271. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38272. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38273. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38274. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38275. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38276. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38277. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38278. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38279. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38280. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38281. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38282. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38283. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38284. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38285. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38286. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38287. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38288. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38289. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38290. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38291. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38292. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38293. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38294. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38295. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38296. this._uniformBuffer.addUniform("pointSize", 1);
  38297. this._uniformBuffer.create();
  38298. };
  38299. PBRBaseMaterial.prototype.unbind = function () {
  38300. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38301. this._uniformBuffer.setTexture("reflectionSampler", null);
  38302. }
  38303. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38304. this._uniformBuffer.setTexture("refractionSampler", null);
  38305. }
  38306. _super.prototype.unbind.call(this);
  38307. };
  38308. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38309. this._activeEffect.setMatrix("world", world);
  38310. };
  38311. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38312. var scene = this.getScene();
  38313. var defines = subMesh._materialDefines;
  38314. if (!defines) {
  38315. return;
  38316. }
  38317. var effect = subMesh.effect;
  38318. if (!effect) {
  38319. return;
  38320. }
  38321. this._activeEffect = effect;
  38322. // Matrices
  38323. this.bindOnlyWorldMatrix(world);
  38324. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38325. // Bones
  38326. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38327. var reflectionTexture = null;
  38328. if (mustRebind) {
  38329. this._uniformBuffer.bindToEffect(effect, "Material");
  38330. this.bindViewProjection(effect);
  38331. reflectionTexture = this._getReflectionTexture();
  38332. var refractionTexture = this._getRefractionTexture();
  38333. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38334. // Texture uniforms
  38335. if (scene.texturesEnabled) {
  38336. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38337. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38338. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38339. }
  38340. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38341. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38342. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38343. }
  38344. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38345. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38346. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38347. }
  38348. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38349. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38350. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38351. var polynomials = reflectionTexture.sphericalPolynomial;
  38352. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38353. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38354. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38355. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38356. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38357. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38358. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38359. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38360. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38361. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38362. }
  38363. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38364. }
  38365. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38366. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38367. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38368. }
  38369. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38370. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38371. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38372. }
  38373. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38374. if (this._metallicTexture) {
  38375. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38376. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38377. }
  38378. else if (this._reflectivityTexture) {
  38379. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38380. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38381. }
  38382. if (this._microSurfaceTexture) {
  38383. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38384. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38385. }
  38386. }
  38387. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38388. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38389. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38390. if (scene._mirroredCameraPosition) {
  38391. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38392. }
  38393. else {
  38394. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38395. }
  38396. }
  38397. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38398. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38399. var depth = 1.0;
  38400. if (!refractionTexture.isCube) {
  38401. if (refractionTexture.depth) {
  38402. depth = refractionTexture.depth;
  38403. }
  38404. }
  38405. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38406. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38407. }
  38408. }
  38409. // Point size
  38410. if (this.pointsCloud) {
  38411. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38412. }
  38413. // Colors
  38414. if (defines.METALLICWORKFLOW) {
  38415. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38416. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38417. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38418. }
  38419. else {
  38420. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38421. }
  38422. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38423. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38424. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38425. // Misc
  38426. this._lightingInfos.x = this._directIntensity;
  38427. this._lightingInfos.y = this._emissiveIntensity;
  38428. this._lightingInfos.z = this._environmentIntensity;
  38429. this._lightingInfos.w = this._specularIntensity;
  38430. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38431. }
  38432. // Textures
  38433. if (scene.texturesEnabled) {
  38434. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38435. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38436. }
  38437. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38438. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38439. }
  38440. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38441. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38442. }
  38443. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38444. if (defines.LODBASEDMICROSFURACE) {
  38445. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38446. }
  38447. else {
  38448. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38449. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38450. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38451. }
  38452. }
  38453. if (defines.ENVIRONMENTBRDF) {
  38454. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38455. }
  38456. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38457. if (defines.LODBASEDMICROSFURACE) {
  38458. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  38459. }
  38460. else {
  38461. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  38462. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  38463. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  38464. }
  38465. }
  38466. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38467. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  38468. }
  38469. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38470. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  38471. }
  38472. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38473. if (this._metallicTexture) {
  38474. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  38475. }
  38476. else if (this._reflectivityTexture) {
  38477. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  38478. }
  38479. if (this._microSurfaceTexture) {
  38480. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  38481. }
  38482. }
  38483. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38484. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  38485. }
  38486. }
  38487. // Clip plane
  38488. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  38489. // Colors
  38490. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  38491. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38492. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  38493. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  38494. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38495. }
  38496. if (mustRebind || !this.isFrozen) {
  38497. // Lights
  38498. if (scene.lightsEnabled && !this._disableLighting) {
  38499. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  38500. }
  38501. // View
  38502. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  38503. this.bindView(effect);
  38504. }
  38505. // Fog
  38506. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  38507. // Morph targets
  38508. if (defines.NUM_MORPH_INFLUENCERS) {
  38509. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  38510. }
  38511. // image processing
  38512. this._imageProcessingConfiguration.bind(this._activeEffect);
  38513. // Log. depth
  38514. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  38515. }
  38516. this._uniformBuffer.update();
  38517. this._afterBind(mesh);
  38518. };
  38519. PBRBaseMaterial.prototype.getAnimatables = function () {
  38520. var results = [];
  38521. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  38522. results.push(this._albedoTexture);
  38523. }
  38524. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38525. results.push(this._ambientTexture);
  38526. }
  38527. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38528. results.push(this._opacityTexture);
  38529. }
  38530. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38531. results.push(this._reflectionTexture);
  38532. }
  38533. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38534. results.push(this._emissiveTexture);
  38535. }
  38536. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  38537. results.push(this._metallicTexture);
  38538. }
  38539. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  38540. results.push(this._reflectivityTexture);
  38541. }
  38542. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38543. results.push(this._bumpTexture);
  38544. }
  38545. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38546. results.push(this._lightmapTexture);
  38547. }
  38548. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38549. results.push(this._refractionTexture);
  38550. }
  38551. return results;
  38552. };
  38553. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38554. if (this._reflectionTexture) {
  38555. return this._reflectionTexture;
  38556. }
  38557. return this.getScene().environmentTexture;
  38558. };
  38559. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38560. if (this._refractionTexture) {
  38561. return this._refractionTexture;
  38562. }
  38563. if (this._linkRefractionWithTransparency) {
  38564. return this.getScene().environmentTexture;
  38565. }
  38566. return null;
  38567. };
  38568. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38569. if (forceDisposeTextures) {
  38570. if (this._albedoTexture) {
  38571. this._albedoTexture.dispose();
  38572. }
  38573. if (this._ambientTexture) {
  38574. this._ambientTexture.dispose();
  38575. }
  38576. if (this._opacityTexture) {
  38577. this._opacityTexture.dispose();
  38578. }
  38579. if (this._reflectionTexture) {
  38580. this._reflectionTexture.dispose();
  38581. }
  38582. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  38583. this._environmentBRDFTexture.dispose();
  38584. }
  38585. if (this._emissiveTexture) {
  38586. this._emissiveTexture.dispose();
  38587. }
  38588. if (this._metallicTexture) {
  38589. this._metallicTexture.dispose();
  38590. }
  38591. if (this._reflectivityTexture) {
  38592. this._reflectivityTexture.dispose();
  38593. }
  38594. if (this._bumpTexture) {
  38595. this._bumpTexture.dispose();
  38596. }
  38597. if (this._lightmapTexture) {
  38598. this._lightmapTexture.dispose();
  38599. }
  38600. if (this._refractionTexture) {
  38601. this._refractionTexture.dispose();
  38602. }
  38603. }
  38604. this._renderTargets.dispose();
  38605. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38606. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38607. }
  38608. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38609. };
  38610. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38611. __decorate([
  38612. BABYLON.serializeAsImageProcessingConfiguration()
  38613. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38614. __decorate([
  38615. BABYLON.serialize()
  38616. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38617. __decorate([
  38618. BABYLON.serialize()
  38619. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  38620. return PBRBaseMaterial;
  38621. }(BABYLON.PushMaterial));
  38622. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38623. })(BABYLON || (BABYLON = {}));
  38624. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38625. var BABYLON;
  38626. (function (BABYLON) {
  38627. /**
  38628. * The Physically based simple base material of BJS.
  38629. *
  38630. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38631. * It is used as the base class for both the specGloss and metalRough conventions.
  38632. */
  38633. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  38634. __extends(PBRBaseSimpleMaterial, _super);
  38635. /**
  38636. * Instantiates a new PBRMaterial instance.
  38637. *
  38638. * @param name The material name
  38639. * @param scene The scene the material will be use in.
  38640. */
  38641. function PBRBaseSimpleMaterial(name, scene) {
  38642. var _this = _super.call(this, name, scene) || this;
  38643. /**
  38644. * Number of Simultaneous lights allowed on the material.
  38645. */
  38646. _this.maxSimultaneousLights = 4;
  38647. /**
  38648. * If sets to true, disables all the lights affecting the material.
  38649. */
  38650. _this.disableLighting = false;
  38651. /**
  38652. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38653. */
  38654. _this.invertNormalMapX = false;
  38655. /**
  38656. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38657. */
  38658. _this.invertNormalMapY = false;
  38659. /**
  38660. * Emissivie color used to self-illuminate the model.
  38661. */
  38662. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38663. /**
  38664. * Occlusion Channel Strenght.
  38665. */
  38666. _this.occlusionStrength = 1.0;
  38667. _this.useLightmapAsShadowmap = false;
  38668. _this._useAlphaFromAlbedoTexture = true;
  38669. _this._useAmbientInGrayScale = true;
  38670. return _this;
  38671. }
  38672. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38673. /**
  38674. * Gets the current double sided mode.
  38675. */
  38676. get: function () {
  38677. return this._twoSidedLighting;
  38678. },
  38679. /**
  38680. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38681. */
  38682. set: function (value) {
  38683. if (this._twoSidedLighting === value) {
  38684. return;
  38685. }
  38686. this._twoSidedLighting = value;
  38687. this.backFaceCulling = !value;
  38688. this._markAllSubMeshesAsTexturesDirty();
  38689. },
  38690. enumerable: true,
  38691. configurable: true
  38692. });
  38693. /**
  38694. * Return the active textures of the material.
  38695. */
  38696. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38697. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38698. if (this.environmentTexture) {
  38699. activeTextures.push(this.environmentTexture);
  38700. }
  38701. if (this.normalTexture) {
  38702. activeTextures.push(this.normalTexture);
  38703. }
  38704. if (this.emissiveTexture) {
  38705. activeTextures.push(this.emissiveTexture);
  38706. }
  38707. if (this.occlusionTexture) {
  38708. activeTextures.push(this.occlusionTexture);
  38709. }
  38710. if (this.lightmapTexture) {
  38711. activeTextures.push(this.lightmapTexture);
  38712. }
  38713. return activeTextures;
  38714. };
  38715. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  38716. if (_super.prototype.hasTexture.call(this, texture)) {
  38717. return true;
  38718. }
  38719. if (this.lightmapTexture === texture) {
  38720. return true;
  38721. }
  38722. return false;
  38723. };
  38724. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38725. return "PBRBaseSimpleMaterial";
  38726. };
  38727. __decorate([
  38728. BABYLON.serialize(),
  38729. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38730. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38731. __decorate([
  38732. BABYLON.serialize(),
  38733. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38734. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38735. __decorate([
  38736. BABYLON.serializeAsTexture(),
  38737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38738. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38739. __decorate([
  38740. BABYLON.serialize(),
  38741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38742. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38743. __decorate([
  38744. BABYLON.serialize(),
  38745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38746. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38747. __decorate([
  38748. BABYLON.serializeAsTexture(),
  38749. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38750. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38751. __decorate([
  38752. BABYLON.serializeAsColor3("emissive"),
  38753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38754. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38755. __decorate([
  38756. BABYLON.serializeAsTexture(),
  38757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38758. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38759. __decorate([
  38760. BABYLON.serialize(),
  38761. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38762. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38763. __decorate([
  38764. BABYLON.serializeAsTexture(),
  38765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38766. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38767. __decorate([
  38768. BABYLON.serialize(),
  38769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38770. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  38771. __decorate([
  38772. BABYLON.serialize()
  38773. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  38774. __decorate([
  38775. BABYLON.serializeAsTexture(),
  38776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38777. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  38778. __decorate([
  38779. BABYLON.serialize(),
  38780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38781. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38782. return PBRBaseSimpleMaterial;
  38783. }(BABYLON.PBRBaseMaterial));
  38784. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  38785. })(BABYLON || (BABYLON = {}));
  38786. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  38787. var BABYLON;
  38788. (function (BABYLON) {
  38789. /**
  38790. * The Physically based material of BJS.
  38791. *
  38792. * This offers the main features of a standard PBR material.
  38793. * For more information, please refer to the documentation :
  38794. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38795. */
  38796. var PBRMaterial = /** @class */ (function (_super) {
  38797. __extends(PBRMaterial, _super);
  38798. /**
  38799. * Instantiates a new PBRMaterial instance.
  38800. *
  38801. * @param name The material name
  38802. * @param scene The scene the material will be use in.
  38803. */
  38804. function PBRMaterial(name, scene) {
  38805. var _this = _super.call(this, name, scene) || this;
  38806. /**
  38807. * Intensity of the direct lights e.g. the four lights available in your scene.
  38808. * This impacts both the direct diffuse and specular highlights.
  38809. */
  38810. _this.directIntensity = 1.0;
  38811. /**
  38812. * Intensity of the emissive part of the material.
  38813. * This helps controlling the emissive effect without modifying the emissive color.
  38814. */
  38815. _this.emissiveIntensity = 1.0;
  38816. /**
  38817. * Intensity of the environment e.g. how much the environment will light the object
  38818. * either through harmonics for rough material or through the refelction for shiny ones.
  38819. */
  38820. _this.environmentIntensity = 1.0;
  38821. /**
  38822. * This is a special control allowing the reduction of the specular highlights coming from the
  38823. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38824. */
  38825. _this.specularIntensity = 1.0;
  38826. /**
  38827. * Debug Control allowing disabling the bump map on this material.
  38828. */
  38829. _this.disableBumpMap = false;
  38830. /**
  38831. * AKA Occlusion Texture Intensity in other nomenclature.
  38832. */
  38833. _this.ambientTextureStrength = 1.0;
  38834. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38835. /**
  38836. * AKA Diffuse Color in other nomenclature.
  38837. */
  38838. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  38839. /**
  38840. * AKA Specular Color in other nomenclature.
  38841. */
  38842. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38843. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  38844. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38845. /**
  38846. * AKA Glossiness in other nomenclature.
  38847. */
  38848. _this.microSurface = 1.0;
  38849. /**
  38850. * source material index of refraction (IOR)' / 'destination material IOR.
  38851. */
  38852. _this.indexOfRefraction = 0.66;
  38853. /**
  38854. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38855. */
  38856. _this.invertRefractionY = false;
  38857. /**
  38858. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38859. * Materials half opaque for instance using refraction could benefit from this control.
  38860. */
  38861. _this.linkRefractionWithTransparency = false;
  38862. _this.useLightmapAsShadowmap = false;
  38863. /**
  38864. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  38865. */
  38866. _this.useAlphaFromAlbedoTexture = false;
  38867. /**
  38868. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38869. */
  38870. _this.forceAlphaTest = false;
  38871. /**
  38872. * Defines the alpha limits in alpha test mode.
  38873. */
  38874. _this.alphaCutOff = 0.4;
  38875. /**
  38876. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38877. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38878. */
  38879. _this.useSpecularOverAlpha = true;
  38880. /**
  38881. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38882. */
  38883. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  38884. /**
  38885. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38886. */
  38887. _this.useRoughnessFromMetallicTextureAlpha = true;
  38888. /**
  38889. * Specifies if the metallic texture contains the roughness information in its green channel.
  38890. */
  38891. _this.useRoughnessFromMetallicTextureGreen = false;
  38892. /**
  38893. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38894. */
  38895. _this.useMetallnessFromMetallicTextureBlue = false;
  38896. /**
  38897. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38898. */
  38899. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38900. /**
  38901. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38902. */
  38903. _this.useAmbientInGrayScale = false;
  38904. /**
  38905. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38906. * The material will try to infer what glossiness each pixel should be.
  38907. */
  38908. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38909. /**
  38910. * BJS is using an harcoded light falloff based on a manually sets up range.
  38911. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38912. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38913. */
  38914. _this.usePhysicalLightFalloff = true;
  38915. /**
  38916. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38917. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38918. */
  38919. _this.useRadianceOverAlpha = true;
  38920. /**
  38921. * Allows using the bump map in parallax mode.
  38922. */
  38923. _this.useParallax = false;
  38924. /**
  38925. * Allows using the bump map in parallax occlusion mode.
  38926. */
  38927. _this.useParallaxOcclusion = false;
  38928. /**
  38929. * Controls the scale bias of the parallax mode.
  38930. */
  38931. _this.parallaxScaleBias = 0.05;
  38932. /**
  38933. * If sets to true, disables all the lights affecting the material.
  38934. */
  38935. _this.disableLighting = false;
  38936. /**
  38937. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38938. */
  38939. _this.forceIrradianceInFragment = false;
  38940. /**
  38941. * Number of Simultaneous lights allowed on the material.
  38942. */
  38943. _this.maxSimultaneousLights = 4;
  38944. /**
  38945. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38946. */
  38947. _this.invertNormalMapX = false;
  38948. /**
  38949. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38950. */
  38951. _this.invertNormalMapY = false;
  38952. /**
  38953. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38954. */
  38955. _this.twoSidedLighting = false;
  38956. /**
  38957. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38958. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38959. */
  38960. _this.useAlphaFresnel = false;
  38961. /**
  38962. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38963. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38964. */
  38965. _this.useLinearAlphaFresnel = false;
  38966. /**
  38967. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38968. * And/Or occlude the blended part.
  38969. */
  38970. _this.environmentBRDFTexture = null;
  38971. /**
  38972. * Force normal to face away from face.
  38973. */
  38974. _this.forceNormalForward = false;
  38975. /**
  38976. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38977. * makes the reflect vector face the model (under horizon).
  38978. */
  38979. _this.useHorizonOcclusion = true;
  38980. /**
  38981. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38982. * too much the area relying on ambient texture to define their ambient occlusion.
  38983. */
  38984. _this.useRadianceOcclusion = true;
  38985. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38986. return _this;
  38987. }
  38988. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38989. /**
  38990. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38991. */
  38992. get: function () {
  38993. return this._PBRMATERIAL_OPAQUE;
  38994. },
  38995. enumerable: true,
  38996. configurable: true
  38997. });
  38998. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38999. /**
  39000. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39001. */
  39002. get: function () {
  39003. return this._PBRMATERIAL_ALPHATEST;
  39004. },
  39005. enumerable: true,
  39006. configurable: true
  39007. });
  39008. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39009. /**
  39010. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39011. */
  39012. get: function () {
  39013. return this._PBRMATERIAL_ALPHABLEND;
  39014. },
  39015. enumerable: true,
  39016. configurable: true
  39017. });
  39018. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39019. /**
  39020. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39021. * They are also discarded below the alpha cutoff threshold to improve performances.
  39022. */
  39023. get: function () {
  39024. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39025. },
  39026. enumerable: true,
  39027. configurable: true
  39028. });
  39029. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39030. /**
  39031. * Gets the image processing configuration used either in this material.
  39032. */
  39033. get: function () {
  39034. return this._imageProcessingConfiguration;
  39035. },
  39036. /**
  39037. * Sets the Default image processing configuration used either in the this material.
  39038. *
  39039. * If sets to null, the scene one is in use.
  39040. */
  39041. set: function (value) {
  39042. this._attachImageProcessingConfiguration(value);
  39043. // Ensure the effect will be rebuilt.
  39044. this._markAllSubMeshesAsTexturesDirty();
  39045. },
  39046. enumerable: true,
  39047. configurable: true
  39048. });
  39049. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39050. /**
  39051. * Gets wether the color curves effect is enabled.
  39052. */
  39053. get: function () {
  39054. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39055. },
  39056. /**
  39057. * Sets wether the color curves effect is enabled.
  39058. */
  39059. set: function (value) {
  39060. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39061. },
  39062. enumerable: true,
  39063. configurable: true
  39064. });
  39065. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39066. /**
  39067. * Gets wether the color grading effect is enabled.
  39068. */
  39069. get: function () {
  39070. return this.imageProcessingConfiguration.colorGradingEnabled;
  39071. },
  39072. /**
  39073. * Gets wether the color grading effect is enabled.
  39074. */
  39075. set: function (value) {
  39076. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39077. },
  39078. enumerable: true,
  39079. configurable: true
  39080. });
  39081. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39082. /**
  39083. * Gets wether tonemapping is enabled or not.
  39084. */
  39085. get: function () {
  39086. return this._imageProcessingConfiguration.toneMappingEnabled;
  39087. },
  39088. /**
  39089. * Sets wether tonemapping is enabled or not
  39090. */
  39091. set: function (value) {
  39092. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39093. },
  39094. enumerable: true,
  39095. configurable: true
  39096. });
  39097. ;
  39098. ;
  39099. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39100. /**
  39101. * The camera exposure used on this material.
  39102. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39103. * This corresponds to a photographic exposure.
  39104. */
  39105. get: function () {
  39106. return this._imageProcessingConfiguration.exposure;
  39107. },
  39108. /**
  39109. * The camera exposure used on this material.
  39110. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39111. * This corresponds to a photographic exposure.
  39112. */
  39113. set: function (value) {
  39114. this._imageProcessingConfiguration.exposure = value;
  39115. },
  39116. enumerable: true,
  39117. configurable: true
  39118. });
  39119. ;
  39120. ;
  39121. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39122. /**
  39123. * Gets The camera contrast used on this material.
  39124. */
  39125. get: function () {
  39126. return this._imageProcessingConfiguration.contrast;
  39127. },
  39128. /**
  39129. * Sets The camera contrast used on this material.
  39130. */
  39131. set: function (value) {
  39132. this._imageProcessingConfiguration.contrast = value;
  39133. },
  39134. enumerable: true,
  39135. configurable: true
  39136. });
  39137. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39138. /**
  39139. * Gets the Color Grading 2D Lookup Texture.
  39140. */
  39141. get: function () {
  39142. return this._imageProcessingConfiguration.colorGradingTexture;
  39143. },
  39144. /**
  39145. * Sets the Color Grading 2D Lookup Texture.
  39146. */
  39147. set: function (value) {
  39148. this._imageProcessingConfiguration.colorGradingTexture = value;
  39149. },
  39150. enumerable: true,
  39151. configurable: true
  39152. });
  39153. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39154. /**
  39155. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39156. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39157. * 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;
  39158. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39159. */
  39160. get: function () {
  39161. return this._imageProcessingConfiguration.colorCurves;
  39162. },
  39163. /**
  39164. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39165. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39166. * 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;
  39167. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39168. */
  39169. set: function (value) {
  39170. this._imageProcessingConfiguration.colorCurves = value;
  39171. },
  39172. enumerable: true,
  39173. configurable: true
  39174. });
  39175. PBRMaterial.prototype.getClassName = function () {
  39176. return "PBRMaterial";
  39177. };
  39178. PBRMaterial.prototype.getActiveTextures = function () {
  39179. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39180. if (this._albedoTexture) {
  39181. activeTextures.push(this._albedoTexture);
  39182. }
  39183. if (this._ambientTexture) {
  39184. activeTextures.push(this._ambientTexture);
  39185. }
  39186. if (this._opacityTexture) {
  39187. activeTextures.push(this._opacityTexture);
  39188. }
  39189. if (this._reflectionTexture) {
  39190. activeTextures.push(this._reflectionTexture);
  39191. }
  39192. if (this._emissiveTexture) {
  39193. activeTextures.push(this._emissiveTexture);
  39194. }
  39195. if (this._reflectivityTexture) {
  39196. activeTextures.push(this._reflectivityTexture);
  39197. }
  39198. if (this._metallicTexture) {
  39199. activeTextures.push(this._metallicTexture);
  39200. }
  39201. if (this._microSurfaceTexture) {
  39202. activeTextures.push(this._microSurfaceTexture);
  39203. }
  39204. if (this._bumpTexture) {
  39205. activeTextures.push(this._bumpTexture);
  39206. }
  39207. if (this._lightmapTexture) {
  39208. activeTextures.push(this._lightmapTexture);
  39209. }
  39210. if (this._refractionTexture) {
  39211. activeTextures.push(this._refractionTexture);
  39212. }
  39213. return activeTextures;
  39214. };
  39215. PBRMaterial.prototype.hasTexture = function (texture) {
  39216. if (_super.prototype.hasTexture.call(this, texture)) {
  39217. return true;
  39218. }
  39219. if (this._albedoTexture === texture) {
  39220. return true;
  39221. }
  39222. if (this._ambientTexture === texture) {
  39223. return true;
  39224. }
  39225. if (this._opacityTexture === texture) {
  39226. return true;
  39227. }
  39228. if (this._reflectionTexture === texture) {
  39229. return true;
  39230. }
  39231. if (this._reflectivityTexture === texture) {
  39232. return true;
  39233. }
  39234. if (this._metallicTexture === texture) {
  39235. return true;
  39236. }
  39237. if (this._microSurfaceTexture === texture) {
  39238. return true;
  39239. }
  39240. if (this._bumpTexture === texture) {
  39241. return true;
  39242. }
  39243. if (this._lightmapTexture === texture) {
  39244. return true;
  39245. }
  39246. if (this._refractionTexture === texture) {
  39247. return true;
  39248. }
  39249. return false;
  39250. };
  39251. PBRMaterial.prototype.clone = function (name) {
  39252. var _this = this;
  39253. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39254. clone.id = name;
  39255. clone.name = name;
  39256. return clone;
  39257. };
  39258. PBRMaterial.prototype.serialize = function () {
  39259. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39260. serializationObject.customType = "BABYLON.PBRMaterial";
  39261. return serializationObject;
  39262. };
  39263. // Statics
  39264. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39265. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39266. };
  39267. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39268. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39269. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39270. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39271. __decorate([
  39272. BABYLON.serialize(),
  39273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39274. ], PBRMaterial.prototype, "directIntensity", void 0);
  39275. __decorate([
  39276. BABYLON.serialize(),
  39277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39278. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39279. __decorate([
  39280. BABYLON.serialize(),
  39281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39282. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39283. __decorate([
  39284. BABYLON.serialize(),
  39285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39286. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39287. __decorate([
  39288. BABYLON.serialize(),
  39289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39290. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39291. __decorate([
  39292. BABYLON.serializeAsTexture(),
  39293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39294. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39295. __decorate([
  39296. BABYLON.serializeAsTexture(),
  39297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39298. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39299. __decorate([
  39300. BABYLON.serialize(),
  39301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39302. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39303. __decorate([
  39304. BABYLON.serializeAsTexture(),
  39305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39306. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39307. __decorate([
  39308. BABYLON.serializeAsTexture(),
  39309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39310. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39311. __decorate([
  39312. BABYLON.serializeAsTexture(),
  39313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39314. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39315. __decorate([
  39316. BABYLON.serializeAsTexture(),
  39317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39318. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39319. __decorate([
  39320. BABYLON.serializeAsTexture(),
  39321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39322. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39323. __decorate([
  39324. BABYLON.serialize(),
  39325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39326. ], PBRMaterial.prototype, "metallic", void 0);
  39327. __decorate([
  39328. BABYLON.serialize(),
  39329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39330. ], PBRMaterial.prototype, "roughness", void 0);
  39331. __decorate([
  39332. BABYLON.serializeAsTexture(),
  39333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39334. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39335. __decorate([
  39336. BABYLON.serializeAsTexture(),
  39337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39338. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39339. __decorate([
  39340. BABYLON.serializeAsTexture(),
  39341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39342. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39343. __decorate([
  39344. BABYLON.serializeAsTexture(),
  39345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39346. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39347. __decorate([
  39348. BABYLON.serializeAsColor3("ambient"),
  39349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39350. ], PBRMaterial.prototype, "ambientColor", void 0);
  39351. __decorate([
  39352. BABYLON.serializeAsColor3("albedo"),
  39353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39354. ], PBRMaterial.prototype, "albedoColor", void 0);
  39355. __decorate([
  39356. BABYLON.serializeAsColor3("reflectivity"),
  39357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39358. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39359. __decorate([
  39360. BABYLON.serializeAsColor3("reflection"),
  39361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39362. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39363. __decorate([
  39364. BABYLON.serializeAsColor3("emissive"),
  39365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39366. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39367. __decorate([
  39368. BABYLON.serialize(),
  39369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39370. ], PBRMaterial.prototype, "microSurface", void 0);
  39371. __decorate([
  39372. BABYLON.serialize(),
  39373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39374. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39375. __decorate([
  39376. BABYLON.serialize(),
  39377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39378. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39379. __decorate([
  39380. BABYLON.serialize(),
  39381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39382. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39383. __decorate([
  39384. BABYLON.serialize(),
  39385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39386. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39387. __decorate([
  39388. BABYLON.serialize(),
  39389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39390. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39391. __decorate([
  39392. BABYLON.serialize(),
  39393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39394. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39395. __decorate([
  39396. BABYLON.serialize(),
  39397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39398. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39399. __decorate([
  39400. BABYLON.serialize(),
  39401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39402. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39403. __decorate([
  39404. BABYLON.serialize(),
  39405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39406. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39407. __decorate([
  39408. BABYLON.serialize(),
  39409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39410. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39411. __decorate([
  39412. BABYLON.serialize(),
  39413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39414. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39415. __decorate([
  39416. BABYLON.serialize(),
  39417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39418. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39419. __decorate([
  39420. BABYLON.serialize(),
  39421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39422. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39423. __decorate([
  39424. BABYLON.serialize(),
  39425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39426. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39427. __decorate([
  39428. BABYLON.serialize(),
  39429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39430. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39431. __decorate([
  39432. BABYLON.serialize(),
  39433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39434. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39435. __decorate([
  39436. BABYLON.serialize(),
  39437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39438. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39439. __decorate([
  39440. BABYLON.serialize(),
  39441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39442. ], PBRMaterial.prototype, "useParallax", void 0);
  39443. __decorate([
  39444. BABYLON.serialize(),
  39445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39446. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39447. __decorate([
  39448. BABYLON.serialize(),
  39449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39450. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39451. __decorate([
  39452. BABYLON.serialize(),
  39453. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39454. ], PBRMaterial.prototype, "disableLighting", void 0);
  39455. __decorate([
  39456. BABYLON.serialize(),
  39457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39458. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  39459. __decorate([
  39460. BABYLON.serialize(),
  39461. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39462. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39463. __decorate([
  39464. BABYLON.serialize(),
  39465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39466. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39467. __decorate([
  39468. BABYLON.serialize(),
  39469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39470. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39471. __decorate([
  39472. BABYLON.serialize(),
  39473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39474. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39475. __decorate([
  39476. BABYLON.serialize(),
  39477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39478. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  39479. __decorate([
  39480. BABYLON.serialize(),
  39481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39482. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  39483. __decorate([
  39484. BABYLON.serializeAsTexture(),
  39485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39486. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  39487. __decorate([
  39488. BABYLON.serialize(),
  39489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39490. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  39491. __decorate([
  39492. BABYLON.serialize(),
  39493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39494. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  39495. __decorate([
  39496. BABYLON.serialize(),
  39497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39498. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  39499. return PBRMaterial;
  39500. }(BABYLON.PBRBaseMaterial));
  39501. BABYLON.PBRMaterial = PBRMaterial;
  39502. })(BABYLON || (BABYLON = {}));
  39503. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39504. var BABYLON;
  39505. (function (BABYLON) {
  39506. /**
  39507. * The PBR material of BJS following the metal roughness convention.
  39508. *
  39509. * This fits to the PBR convention in the GLTF definition:
  39510. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39511. */
  39512. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  39513. __extends(PBRMetallicRoughnessMaterial, _super);
  39514. /**
  39515. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39516. *
  39517. * @param name The material name
  39518. * @param scene The scene the material will be use in.
  39519. */
  39520. function PBRMetallicRoughnessMaterial(name, scene) {
  39521. var _this = _super.call(this, name, scene) || this;
  39522. _this._useRoughnessFromMetallicTextureAlpha = false;
  39523. _this._useRoughnessFromMetallicTextureGreen = true;
  39524. _this._useMetallnessFromMetallicTextureBlue = true;
  39525. _this._forceMetallicWorkflow = true;
  39526. return _this;
  39527. }
  39528. /**
  39529. * Return the currrent class name of the material.
  39530. */
  39531. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39532. return "PBRMetallicRoughnessMaterial";
  39533. };
  39534. /**
  39535. * Return the active textures of the material.
  39536. */
  39537. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39538. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39539. if (this.baseTexture) {
  39540. activeTextures.push(this.baseTexture);
  39541. }
  39542. if (this.metallicRoughnessTexture) {
  39543. activeTextures.push(this.metallicRoughnessTexture);
  39544. }
  39545. return activeTextures;
  39546. };
  39547. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39548. if (_super.prototype.hasTexture.call(this, texture)) {
  39549. return true;
  39550. }
  39551. if (this.baseTexture === texture) {
  39552. return true;
  39553. }
  39554. if (this.metallicRoughnessTexture === texture) {
  39555. return true;
  39556. }
  39557. return false;
  39558. };
  39559. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39560. var _this = this;
  39561. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39562. clone.id = name;
  39563. clone.name = name;
  39564. return clone;
  39565. };
  39566. /**
  39567. * Serialize the material to a parsable JSON object.
  39568. */
  39569. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39570. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39571. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39572. return serializationObject;
  39573. };
  39574. /**
  39575. * Parses a JSON object correponding to the serialize function.
  39576. */
  39577. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39578. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39579. };
  39580. __decorate([
  39581. BABYLON.serializeAsColor3(),
  39582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39583. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39584. __decorate([
  39585. BABYLON.serializeAsTexture(),
  39586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39587. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39588. __decorate([
  39589. BABYLON.serialize(),
  39590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39591. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39592. __decorate([
  39593. BABYLON.serialize(),
  39594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39595. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39596. __decorate([
  39597. BABYLON.serializeAsTexture(),
  39598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39599. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39600. return PBRMetallicRoughnessMaterial;
  39601. }(BABYLON.PBRBaseSimpleMaterial));
  39602. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39603. })(BABYLON || (BABYLON = {}));
  39604. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39605. var BABYLON;
  39606. (function (BABYLON) {
  39607. /**
  39608. * The PBR material of BJS following the specular glossiness convention.
  39609. *
  39610. * This fits to the PBR convention in the GLTF definition:
  39611. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39612. */
  39613. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  39614. __extends(PBRSpecularGlossinessMaterial, _super);
  39615. /**
  39616. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39617. *
  39618. * @param name The material name
  39619. * @param scene The scene the material will be use in.
  39620. */
  39621. function PBRSpecularGlossinessMaterial(name, scene) {
  39622. var _this = _super.call(this, name, scene) || this;
  39623. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39624. return _this;
  39625. }
  39626. /**
  39627. * Return the currrent class name of the material.
  39628. */
  39629. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39630. return "PBRSpecularGlossinessMaterial";
  39631. };
  39632. /**
  39633. * Return the active textures of the material.
  39634. */
  39635. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39636. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39637. if (this.diffuseTexture) {
  39638. activeTextures.push(this.diffuseTexture);
  39639. }
  39640. if (this.specularGlossinessTexture) {
  39641. activeTextures.push(this.specularGlossinessTexture);
  39642. }
  39643. return activeTextures;
  39644. };
  39645. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39646. if (_super.prototype.hasTexture.call(this, texture)) {
  39647. return true;
  39648. }
  39649. if (this.diffuseTexture === texture) {
  39650. return true;
  39651. }
  39652. if (this.specularGlossinessTexture === texture) {
  39653. return true;
  39654. }
  39655. return false;
  39656. };
  39657. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39658. var _this = this;
  39659. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39660. clone.id = name;
  39661. clone.name = name;
  39662. return clone;
  39663. };
  39664. /**
  39665. * Serialize the material to a parsable JSON object.
  39666. */
  39667. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39668. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39669. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39670. return serializationObject;
  39671. };
  39672. /**
  39673. * Parses a JSON object correponding to the serialize function.
  39674. */
  39675. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39676. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39677. };
  39678. __decorate([
  39679. BABYLON.serializeAsColor3("diffuse"),
  39680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39681. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39682. __decorate([
  39683. BABYLON.serializeAsTexture(),
  39684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39685. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39686. __decorate([
  39687. BABYLON.serializeAsColor3("specular"),
  39688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39689. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39690. __decorate([
  39691. BABYLON.serialize(),
  39692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39693. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39694. __decorate([
  39695. BABYLON.serializeAsTexture(),
  39696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39697. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39698. return PBRSpecularGlossinessMaterial;
  39699. }(BABYLON.PBRBaseSimpleMaterial));
  39700. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39701. })(BABYLON || (BABYLON = {}));
  39702. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39703. var BABYLON;
  39704. (function (BABYLON) {
  39705. BABYLON.CameraInputTypes = {};
  39706. var CameraInputsManager = /** @class */ (function () {
  39707. function CameraInputsManager(camera) {
  39708. this.attached = {};
  39709. this.camera = camera;
  39710. this.checkInputs = function () { };
  39711. }
  39712. /**
  39713. * Add an input method to a camera.
  39714. * builtin inputs example: camera.inputs.addGamepad();
  39715. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  39716. * @param input camera input method
  39717. */
  39718. CameraInputsManager.prototype.add = function (input) {
  39719. var type = input.getSimpleName();
  39720. if (this.attached[type]) {
  39721. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  39722. return;
  39723. }
  39724. this.attached[type] = input;
  39725. input.camera = this.camera;
  39726. //for checkInputs, we are dynamically creating a function
  39727. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  39728. if (input.checkInputs) {
  39729. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39730. }
  39731. if (this.attachedElement) {
  39732. input.attachControl(this.attachedElement);
  39733. }
  39734. };
  39735. /**
  39736. * Remove a specific input method from a camera
  39737. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  39738. * @param inputToRemove camera input method
  39739. */
  39740. CameraInputsManager.prototype.remove = function (inputToRemove) {
  39741. for (var cam in this.attached) {
  39742. var input = this.attached[cam];
  39743. if (input === inputToRemove) {
  39744. input.detachControl(this.attachedElement);
  39745. input.camera = null;
  39746. delete this.attached[cam];
  39747. this.rebuildInputCheck();
  39748. }
  39749. }
  39750. };
  39751. CameraInputsManager.prototype.removeByType = function (inputType) {
  39752. for (var cam in this.attached) {
  39753. var input = this.attached[cam];
  39754. if (input.getClassName() === inputType) {
  39755. input.detachControl(this.attachedElement);
  39756. input.camera = null;
  39757. delete this.attached[cam];
  39758. this.rebuildInputCheck();
  39759. }
  39760. }
  39761. };
  39762. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  39763. var current = this.checkInputs;
  39764. return function () {
  39765. current();
  39766. fn();
  39767. };
  39768. };
  39769. CameraInputsManager.prototype.attachInput = function (input) {
  39770. if (this.attachedElement) {
  39771. input.attachControl(this.attachedElement, this.noPreventDefault);
  39772. }
  39773. };
  39774. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  39775. if (noPreventDefault === void 0) { noPreventDefault = false; }
  39776. if (this.attachedElement) {
  39777. return;
  39778. }
  39779. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  39780. this.attachedElement = element;
  39781. this.noPreventDefault = noPreventDefault;
  39782. for (var cam in this.attached) {
  39783. this.attached[cam].attachControl(element, noPreventDefault);
  39784. }
  39785. };
  39786. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  39787. if (disconnect === void 0) { disconnect = false; }
  39788. if (this.attachedElement !== element) {
  39789. return;
  39790. }
  39791. for (var cam in this.attached) {
  39792. this.attached[cam].detachControl(element);
  39793. if (disconnect) {
  39794. this.attached[cam].camera = null;
  39795. }
  39796. }
  39797. this.attachedElement = null;
  39798. };
  39799. CameraInputsManager.prototype.rebuildInputCheck = function () {
  39800. this.checkInputs = function () { };
  39801. for (var cam in this.attached) {
  39802. var input = this.attached[cam];
  39803. if (input.checkInputs) {
  39804. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39805. }
  39806. }
  39807. };
  39808. /**
  39809. * Remove all attached input methods from a camera
  39810. */
  39811. CameraInputsManager.prototype.clear = function () {
  39812. if (this.attachedElement) {
  39813. this.detachElement(this.attachedElement, true);
  39814. }
  39815. this.attached = {};
  39816. this.attachedElement = null;
  39817. this.checkInputs = function () { };
  39818. };
  39819. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  39820. var inputs = {};
  39821. for (var cam in this.attached) {
  39822. var input = this.attached[cam];
  39823. var res = BABYLON.SerializationHelper.Serialize(input);
  39824. inputs[input.getClassName()] = res;
  39825. }
  39826. serializedCamera.inputsmgr = inputs;
  39827. };
  39828. CameraInputsManager.prototype.parse = function (parsedCamera) {
  39829. var parsedInputs = parsedCamera.inputsmgr;
  39830. if (parsedInputs) {
  39831. this.clear();
  39832. for (var n in parsedInputs) {
  39833. var construct = BABYLON.CameraInputTypes[n];
  39834. if (construct) {
  39835. var parsedinput = parsedInputs[n];
  39836. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  39837. this.add(input);
  39838. }
  39839. }
  39840. }
  39841. else {
  39842. //2016-03-08 this part is for managing backward compatibility
  39843. for (var n in this.attached) {
  39844. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  39845. if (construct) {
  39846. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  39847. this.remove(this.attached[n]);
  39848. this.add(input);
  39849. }
  39850. }
  39851. }
  39852. };
  39853. return CameraInputsManager;
  39854. }());
  39855. BABYLON.CameraInputsManager = CameraInputsManager;
  39856. })(BABYLON || (BABYLON = {}));
  39857. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  39858. var BABYLON;
  39859. (function (BABYLON) {
  39860. var TargetCamera = /** @class */ (function (_super) {
  39861. __extends(TargetCamera, _super);
  39862. function TargetCamera(name, position, scene) {
  39863. var _this = _super.call(this, name, position, scene) || this;
  39864. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39865. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  39866. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  39867. _this.speed = 2.0;
  39868. _this.noRotationConstraint = false;
  39869. _this.lockedTarget = null;
  39870. _this._currentTarget = BABYLON.Vector3.Zero();
  39871. _this._viewMatrix = BABYLON.Matrix.Zero();
  39872. _this._camMatrix = BABYLON.Matrix.Zero();
  39873. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  39874. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  39875. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  39876. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  39877. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  39878. _this._lookAtTemp = BABYLON.Matrix.Zero();
  39879. _this._tempMatrix = BABYLON.Matrix.Zero();
  39880. return _this;
  39881. }
  39882. TargetCamera.prototype.getFrontPosition = function (distance) {
  39883. this.getWorldMatrix();
  39884. var direction = this.getTarget().subtract(this.position);
  39885. direction.normalize();
  39886. direction.scaleInPlace(distance);
  39887. return this.globalPosition.add(direction);
  39888. };
  39889. TargetCamera.prototype._getLockedTargetPosition = function () {
  39890. if (!this.lockedTarget) {
  39891. return null;
  39892. }
  39893. if (this.lockedTarget.absolutePosition) {
  39894. this.lockedTarget.computeWorldMatrix();
  39895. }
  39896. return this.lockedTarget.absolutePosition || this.lockedTarget;
  39897. };
  39898. TargetCamera.prototype.storeState = function () {
  39899. this._storedPosition = this.position.clone();
  39900. this._storedRotation = this.rotation.clone();
  39901. if (this.rotationQuaternion) {
  39902. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  39903. }
  39904. return _super.prototype.storeState.call(this);
  39905. };
  39906. /**
  39907. * Restored camera state. You must call storeState() first
  39908. */
  39909. TargetCamera.prototype._restoreStateValues = function () {
  39910. if (!_super.prototype._restoreStateValues.call(this)) {
  39911. return false;
  39912. }
  39913. this.position = this._storedPosition.clone();
  39914. this.rotation = this._storedRotation.clone();
  39915. if (this.rotationQuaternion) {
  39916. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  39917. }
  39918. this.cameraDirection.copyFromFloats(0, 0, 0);
  39919. this.cameraRotation.copyFromFloats(0, 0);
  39920. return true;
  39921. };
  39922. // Cache
  39923. TargetCamera.prototype._initCache = function () {
  39924. _super.prototype._initCache.call(this);
  39925. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39926. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39927. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39928. };
  39929. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39930. if (!ignoreParentClass) {
  39931. _super.prototype._updateCache.call(this);
  39932. }
  39933. var lockedTargetPosition = this._getLockedTargetPosition();
  39934. if (!lockedTargetPosition) {
  39935. this._cache.lockedTarget = null;
  39936. }
  39937. else {
  39938. if (!this._cache.lockedTarget) {
  39939. this._cache.lockedTarget = lockedTargetPosition.clone();
  39940. }
  39941. else {
  39942. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39943. }
  39944. }
  39945. this._cache.rotation.copyFrom(this.rotation);
  39946. if (this.rotationQuaternion)
  39947. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39948. };
  39949. // Synchronized
  39950. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39951. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39952. return false;
  39953. }
  39954. var lockedTargetPosition = this._getLockedTargetPosition();
  39955. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39956. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39957. };
  39958. // Methods
  39959. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39960. var engine = this.getEngine();
  39961. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39962. };
  39963. // Target
  39964. TargetCamera.prototype.setTarget = function (target) {
  39965. this.upVector.normalize();
  39966. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39967. this._camMatrix.invert();
  39968. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39969. var vDir = target.subtract(this.position);
  39970. if (vDir.x >= 0.0) {
  39971. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39972. }
  39973. else {
  39974. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39975. }
  39976. this.rotation.z = 0;
  39977. if (isNaN(this.rotation.x)) {
  39978. this.rotation.x = 0;
  39979. }
  39980. if (isNaN(this.rotation.y)) {
  39981. this.rotation.y = 0;
  39982. }
  39983. if (isNaN(this.rotation.z)) {
  39984. this.rotation.z = 0;
  39985. }
  39986. if (this.rotationQuaternion) {
  39987. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39988. }
  39989. };
  39990. /**
  39991. * Return the current target position of the camera. This value is expressed in local space.
  39992. */
  39993. TargetCamera.prototype.getTarget = function () {
  39994. return this._currentTarget;
  39995. };
  39996. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39997. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39998. };
  39999. TargetCamera.prototype._updatePosition = function () {
  40000. if (this.parent) {
  40001. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40002. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40003. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40004. return;
  40005. }
  40006. this.position.addInPlace(this.cameraDirection);
  40007. };
  40008. TargetCamera.prototype._checkInputs = function () {
  40009. var needToMove = this._decideIfNeedsToMove();
  40010. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40011. // Move
  40012. if (needToMove) {
  40013. this._updatePosition();
  40014. }
  40015. // Rotate
  40016. if (needToRotate) {
  40017. this.rotation.x += this.cameraRotation.x;
  40018. this.rotation.y += this.cameraRotation.y;
  40019. //rotate, if quaternion is set and rotation was used
  40020. if (this.rotationQuaternion) {
  40021. var len = this.rotation.lengthSquared();
  40022. if (len) {
  40023. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40024. }
  40025. }
  40026. if (!this.noRotationConstraint) {
  40027. var limit = (Math.PI / 2) * 0.95;
  40028. if (this.rotation.x > limit)
  40029. this.rotation.x = limit;
  40030. if (this.rotation.x < -limit)
  40031. this.rotation.x = -limit;
  40032. }
  40033. }
  40034. // Inertia
  40035. if (needToMove) {
  40036. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40037. this.cameraDirection.x = 0;
  40038. }
  40039. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40040. this.cameraDirection.y = 0;
  40041. }
  40042. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40043. this.cameraDirection.z = 0;
  40044. }
  40045. this.cameraDirection.scaleInPlace(this.inertia);
  40046. }
  40047. if (needToRotate) {
  40048. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40049. this.cameraRotation.x = 0;
  40050. }
  40051. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40052. this.cameraRotation.y = 0;
  40053. }
  40054. this.cameraRotation.scaleInPlace(this.inertia);
  40055. }
  40056. _super.prototype._checkInputs.call(this);
  40057. };
  40058. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40059. if (this.rotationQuaternion) {
  40060. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40061. }
  40062. else {
  40063. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40064. }
  40065. //update the up vector!
  40066. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40067. };
  40068. TargetCamera.prototype._getViewMatrix = function () {
  40069. if (this.lockedTarget) {
  40070. this.setTarget(this._getLockedTargetPosition());
  40071. }
  40072. // Compute
  40073. this._updateCameraRotationMatrix();
  40074. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40075. // Computing target and final matrix
  40076. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40077. if (this.getScene().useRightHandedSystem) {
  40078. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40079. }
  40080. else {
  40081. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40082. }
  40083. return this._viewMatrix;
  40084. };
  40085. /**
  40086. * @override
  40087. * Override Camera.createRigCamera
  40088. */
  40089. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40090. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40091. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40092. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40093. if (!this.rotationQuaternion) {
  40094. this.rotationQuaternion = new BABYLON.Quaternion();
  40095. }
  40096. rigCamera._cameraRigParams = {};
  40097. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40098. }
  40099. return rigCamera;
  40100. }
  40101. return null;
  40102. };
  40103. /**
  40104. * @override
  40105. * Override Camera._updateRigCameras
  40106. */
  40107. TargetCamera.prototype._updateRigCameras = function () {
  40108. var camLeft = this._rigCameras[0];
  40109. var camRight = this._rigCameras[1];
  40110. switch (this.cameraRigMode) {
  40111. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40112. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40113. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40115. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40116. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40117. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40118. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40119. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40120. camLeft.setTarget(this.getTarget());
  40121. camRight.setTarget(this.getTarget());
  40122. break;
  40123. case BABYLON.Camera.RIG_MODE_VR:
  40124. if (camLeft.rotationQuaternion) {
  40125. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40126. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40127. }
  40128. else {
  40129. camLeft.rotation.copyFrom(this.rotation);
  40130. camRight.rotation.copyFrom(this.rotation);
  40131. }
  40132. camLeft.position.copyFrom(this.position);
  40133. camRight.position.copyFrom(this.position);
  40134. break;
  40135. }
  40136. _super.prototype._updateRigCameras.call(this);
  40137. };
  40138. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40139. if (!this._rigCamTransformMatrix) {
  40140. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40141. }
  40142. var target = this.getTarget();
  40143. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40144. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40145. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40146. };
  40147. TargetCamera.prototype.getClassName = function () {
  40148. return "TargetCamera";
  40149. };
  40150. __decorate([
  40151. BABYLON.serializeAsVector3()
  40152. ], TargetCamera.prototype, "rotation", void 0);
  40153. __decorate([
  40154. BABYLON.serialize()
  40155. ], TargetCamera.prototype, "speed", void 0);
  40156. __decorate([
  40157. BABYLON.serializeAsMeshReference("lockedTargetId")
  40158. ], TargetCamera.prototype, "lockedTarget", void 0);
  40159. return TargetCamera;
  40160. }(BABYLON.Camera));
  40161. BABYLON.TargetCamera = TargetCamera;
  40162. })(BABYLON || (BABYLON = {}));
  40163. //# sourceMappingURL=babylon.targetCamera.js.map
  40164. var BABYLON;
  40165. (function (BABYLON) {
  40166. var FreeCameraMouseInput = /** @class */ (function () {
  40167. function FreeCameraMouseInput(touchEnabled) {
  40168. if (touchEnabled === void 0) { touchEnabled = true; }
  40169. this.touchEnabled = touchEnabled;
  40170. this.buttons = [0, 1, 2];
  40171. this.angularSensibility = 2000.0;
  40172. this.previousPosition = null;
  40173. }
  40174. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40175. var _this = this;
  40176. var engine = this.camera.getEngine();
  40177. if (!this._pointerInput) {
  40178. this._pointerInput = function (p, s) {
  40179. var evt = p.event;
  40180. if (engine.isInVRExclusivePointerMode) {
  40181. return;
  40182. }
  40183. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40184. return;
  40185. }
  40186. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40187. return;
  40188. }
  40189. var srcElement = (evt.srcElement || evt.target);
  40190. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40191. try {
  40192. srcElement.setPointerCapture(evt.pointerId);
  40193. }
  40194. catch (e) {
  40195. //Nothing to do with the error. Execution will continue.
  40196. }
  40197. _this.previousPosition = {
  40198. x: evt.clientX,
  40199. y: evt.clientY
  40200. };
  40201. if (!noPreventDefault) {
  40202. evt.preventDefault();
  40203. element.focus();
  40204. }
  40205. }
  40206. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40207. try {
  40208. srcElement.releasePointerCapture(evt.pointerId);
  40209. }
  40210. catch (e) {
  40211. //Nothing to do with the error.
  40212. }
  40213. _this.previousPosition = null;
  40214. if (!noPreventDefault) {
  40215. evt.preventDefault();
  40216. }
  40217. }
  40218. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40219. if (!_this.previousPosition || engine.isPointerLock) {
  40220. return;
  40221. }
  40222. var offsetX = evt.clientX - _this.previousPosition.x;
  40223. var offsetY = evt.clientY - _this.previousPosition.y;
  40224. if (_this.camera.getScene().useRightHandedSystem) {
  40225. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40226. }
  40227. else {
  40228. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40229. }
  40230. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40231. _this.previousPosition = {
  40232. x: evt.clientX,
  40233. y: evt.clientY
  40234. };
  40235. if (!noPreventDefault) {
  40236. evt.preventDefault();
  40237. }
  40238. }
  40239. };
  40240. }
  40241. this._onMouseMove = function (evt) {
  40242. if (!engine.isPointerLock) {
  40243. return;
  40244. }
  40245. if (engine.isInVRExclusivePointerMode) {
  40246. return;
  40247. }
  40248. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40249. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40250. if (_this.camera.getScene().useRightHandedSystem) {
  40251. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40252. }
  40253. else {
  40254. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40255. }
  40256. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40257. _this.previousPosition = null;
  40258. if (!noPreventDefault) {
  40259. evt.preventDefault();
  40260. }
  40261. };
  40262. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40263. element.addEventListener("mousemove", this._onMouseMove, false);
  40264. };
  40265. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40266. if (this._observer && element) {
  40267. this.camera.getScene().onPointerObservable.remove(this._observer);
  40268. if (this._onMouseMove) {
  40269. element.removeEventListener("mousemove", this._onMouseMove);
  40270. }
  40271. this._observer = null;
  40272. this._onMouseMove = null;
  40273. this.previousPosition = null;
  40274. }
  40275. };
  40276. FreeCameraMouseInput.prototype.getClassName = function () {
  40277. return "FreeCameraMouseInput";
  40278. };
  40279. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40280. return "mouse";
  40281. };
  40282. __decorate([
  40283. BABYLON.serialize()
  40284. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40285. __decorate([
  40286. BABYLON.serialize()
  40287. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40288. return FreeCameraMouseInput;
  40289. }());
  40290. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40291. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40292. })(BABYLON || (BABYLON = {}));
  40293. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40294. var BABYLON;
  40295. (function (BABYLON) {
  40296. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40297. function FreeCameraKeyboardMoveInput() {
  40298. this._keys = new Array();
  40299. this.keysUp = [38];
  40300. this.keysDown = [40];
  40301. this.keysLeft = [37];
  40302. this.keysRight = [39];
  40303. }
  40304. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40305. var _this = this;
  40306. if (this._onCanvasBlurObserver) {
  40307. return;
  40308. }
  40309. this._scene = this.camera.getScene();
  40310. this._engine = this._scene.getEngine();
  40311. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40312. _this._keys = [];
  40313. });
  40314. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40315. var evt = info.event;
  40316. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40317. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40318. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40319. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40320. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40321. var index = _this._keys.indexOf(evt.keyCode);
  40322. if (index === -1) {
  40323. _this._keys.push(evt.keyCode);
  40324. }
  40325. if (!noPreventDefault) {
  40326. evt.preventDefault();
  40327. }
  40328. }
  40329. }
  40330. else {
  40331. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40332. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40333. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40334. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40335. var index = _this._keys.indexOf(evt.keyCode);
  40336. if (index >= 0) {
  40337. _this._keys.splice(index, 1);
  40338. }
  40339. if (!noPreventDefault) {
  40340. evt.preventDefault();
  40341. }
  40342. }
  40343. }
  40344. });
  40345. };
  40346. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40347. if (this._scene) {
  40348. if (this._onKeyboardObserver) {
  40349. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40350. }
  40351. if (this._onCanvasBlurObserver) {
  40352. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40353. }
  40354. this._onKeyboardObserver = null;
  40355. this._onCanvasBlurObserver = null;
  40356. }
  40357. this._keys = [];
  40358. };
  40359. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40360. if (this._onKeyboardObserver) {
  40361. var camera = this.camera;
  40362. // Keyboard
  40363. for (var index = 0; index < this._keys.length; index++) {
  40364. var keyCode = this._keys[index];
  40365. var speed = camera._computeLocalCameraSpeed();
  40366. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40367. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40368. }
  40369. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40370. camera._localDirection.copyFromFloats(0, 0, speed);
  40371. }
  40372. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40373. camera._localDirection.copyFromFloats(speed, 0, 0);
  40374. }
  40375. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40376. camera._localDirection.copyFromFloats(0, 0, -speed);
  40377. }
  40378. if (camera.getScene().useRightHandedSystem) {
  40379. camera._localDirection.z *= -1;
  40380. }
  40381. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40382. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40383. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40384. }
  40385. }
  40386. };
  40387. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40388. return "FreeCameraKeyboardMoveInput";
  40389. };
  40390. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40391. this._keys = [];
  40392. };
  40393. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40394. return "keyboard";
  40395. };
  40396. __decorate([
  40397. BABYLON.serialize()
  40398. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40399. __decorate([
  40400. BABYLON.serialize()
  40401. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40402. __decorate([
  40403. BABYLON.serialize()
  40404. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40405. __decorate([
  40406. BABYLON.serialize()
  40407. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40408. return FreeCameraKeyboardMoveInput;
  40409. }());
  40410. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40411. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40412. })(BABYLON || (BABYLON = {}));
  40413. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40414. var BABYLON;
  40415. (function (BABYLON) {
  40416. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40417. __extends(FreeCameraInputsManager, _super);
  40418. function FreeCameraInputsManager(camera) {
  40419. return _super.call(this, camera) || this;
  40420. }
  40421. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40422. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40423. return this;
  40424. };
  40425. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40426. if (touchEnabled === void 0) { touchEnabled = true; }
  40427. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40428. return this;
  40429. };
  40430. FreeCameraInputsManager.prototype.addGamepad = function () {
  40431. this.add(new BABYLON.FreeCameraGamepadInput());
  40432. return this;
  40433. };
  40434. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40435. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40436. return this;
  40437. };
  40438. FreeCameraInputsManager.prototype.addTouch = function () {
  40439. this.add(new BABYLON.FreeCameraTouchInput());
  40440. return this;
  40441. };
  40442. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40443. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40444. return this;
  40445. };
  40446. return FreeCameraInputsManager;
  40447. }(BABYLON.CameraInputsManager));
  40448. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40449. })(BABYLON || (BABYLON = {}));
  40450. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40451. var BABYLON;
  40452. (function (BABYLON) {
  40453. var FreeCamera = /** @class */ (function (_super) {
  40454. __extends(FreeCamera, _super);
  40455. function FreeCamera(name, position, scene) {
  40456. var _this = _super.call(this, name, position, scene) || this;
  40457. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  40458. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  40459. _this.checkCollisions = false;
  40460. _this.applyGravity = false;
  40461. _this._needMoveForGravity = false;
  40462. _this._oldPosition = BABYLON.Vector3.Zero();
  40463. _this._diffPosition = BABYLON.Vector3.Zero();
  40464. _this._newPosition = BABYLON.Vector3.Zero();
  40465. // Collisions
  40466. _this._collisionMask = -1;
  40467. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40468. if (collidedMesh === void 0) { collidedMesh = null; }
  40469. //TODO move this to the collision coordinator!
  40470. if (_this.getScene().workerCollisions)
  40471. newPosition.multiplyInPlace(_this._collider._radius);
  40472. var updatePosition = function (newPos) {
  40473. _this._newPosition.copyFrom(newPos);
  40474. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  40475. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  40476. _this.position.addInPlace(_this._diffPosition);
  40477. if (_this.onCollide && collidedMesh) {
  40478. _this.onCollide(collidedMesh);
  40479. }
  40480. }
  40481. };
  40482. updatePosition(newPosition);
  40483. };
  40484. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  40485. _this.inputs.addKeyboard().addMouse();
  40486. return _this;
  40487. }
  40488. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  40489. //-- begin properties for backward compatibility for inputs
  40490. /**
  40491. * Gets the input sensibility for a mouse input. (default is 2000.0)
  40492. * Higher values reduce sensitivity.
  40493. */
  40494. get: function () {
  40495. var mouse = this.inputs.attached["mouse"];
  40496. if (mouse)
  40497. return mouse.angularSensibility;
  40498. return 0;
  40499. },
  40500. /**
  40501. * Sets the input sensibility for a mouse input. (default is 2000.0)
  40502. * Higher values reduce sensitivity.
  40503. */
  40504. set: function (value) {
  40505. var mouse = this.inputs.attached["mouse"];
  40506. if (mouse)
  40507. mouse.angularSensibility = value;
  40508. },
  40509. enumerable: true,
  40510. configurable: true
  40511. });
  40512. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  40513. get: function () {
  40514. var keyboard = this.inputs.attached["keyboard"];
  40515. if (keyboard)
  40516. return keyboard.keysUp;
  40517. return [];
  40518. },
  40519. set: function (value) {
  40520. var keyboard = this.inputs.attached["keyboard"];
  40521. if (keyboard)
  40522. keyboard.keysUp = value;
  40523. },
  40524. enumerable: true,
  40525. configurable: true
  40526. });
  40527. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  40528. get: function () {
  40529. var keyboard = this.inputs.attached["keyboard"];
  40530. if (keyboard)
  40531. return keyboard.keysDown;
  40532. return [];
  40533. },
  40534. set: function (value) {
  40535. var keyboard = this.inputs.attached["keyboard"];
  40536. if (keyboard)
  40537. keyboard.keysDown = value;
  40538. },
  40539. enumerable: true,
  40540. configurable: true
  40541. });
  40542. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  40543. get: function () {
  40544. var keyboard = this.inputs.attached["keyboard"];
  40545. if (keyboard)
  40546. return keyboard.keysLeft;
  40547. return [];
  40548. },
  40549. set: function (value) {
  40550. var keyboard = this.inputs.attached["keyboard"];
  40551. if (keyboard)
  40552. keyboard.keysLeft = value;
  40553. },
  40554. enumerable: true,
  40555. configurable: true
  40556. });
  40557. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  40558. get: function () {
  40559. var keyboard = this.inputs.attached["keyboard"];
  40560. if (keyboard)
  40561. return keyboard.keysRight;
  40562. return [];
  40563. },
  40564. set: function (value) {
  40565. var keyboard = this.inputs.attached["keyboard"];
  40566. if (keyboard)
  40567. keyboard.keysRight = value;
  40568. },
  40569. enumerable: true,
  40570. configurable: true
  40571. });
  40572. // Controls
  40573. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  40574. this.inputs.attachElement(element, noPreventDefault);
  40575. };
  40576. FreeCamera.prototype.detachControl = function (element) {
  40577. this.inputs.detachElement(element);
  40578. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40579. this.cameraRotation = new BABYLON.Vector2(0, 0);
  40580. };
  40581. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  40582. get: function () {
  40583. return this._collisionMask;
  40584. },
  40585. set: function (mask) {
  40586. this._collisionMask = !isNaN(mask) ? mask : -1;
  40587. },
  40588. enumerable: true,
  40589. configurable: true
  40590. });
  40591. FreeCamera.prototype._collideWithWorld = function (displacement) {
  40592. var globalPosition;
  40593. if (this.parent) {
  40594. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  40595. }
  40596. else {
  40597. globalPosition = this.position;
  40598. }
  40599. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  40600. this._oldPosition.addInPlace(this.ellipsoidOffset);
  40601. if (!this._collider) {
  40602. this._collider = new BABYLON.Collider();
  40603. }
  40604. this._collider._radius = this.ellipsoid;
  40605. this._collider.collisionMask = this._collisionMask;
  40606. //no need for clone, as long as gravity is not on.
  40607. var actualDisplacement = displacement;
  40608. //add gravity to the direction to prevent the dual-collision checking
  40609. if (this.applyGravity) {
  40610. //this prevents mending with cameraDirection, a global variable of the free camera class.
  40611. actualDisplacement = displacement.add(this.getScene().gravity);
  40612. }
  40613. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40614. };
  40615. FreeCamera.prototype._checkInputs = function () {
  40616. if (!this._localDirection) {
  40617. this._localDirection = BABYLON.Vector3.Zero();
  40618. this._transformedDirection = BABYLON.Vector3.Zero();
  40619. }
  40620. this.inputs.checkInputs();
  40621. _super.prototype._checkInputs.call(this);
  40622. };
  40623. FreeCamera.prototype._decideIfNeedsToMove = function () {
  40624. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40625. };
  40626. FreeCamera.prototype._updatePosition = function () {
  40627. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  40628. this._collideWithWorld(this.cameraDirection);
  40629. }
  40630. else {
  40631. _super.prototype._updatePosition.call(this);
  40632. }
  40633. };
  40634. FreeCamera.prototype.dispose = function () {
  40635. this.inputs.clear();
  40636. _super.prototype.dispose.call(this);
  40637. };
  40638. FreeCamera.prototype.getClassName = function () {
  40639. return "FreeCamera";
  40640. };
  40641. __decorate([
  40642. BABYLON.serializeAsVector3()
  40643. ], FreeCamera.prototype, "ellipsoid", void 0);
  40644. __decorate([
  40645. BABYLON.serializeAsVector3()
  40646. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  40647. __decorate([
  40648. BABYLON.serialize()
  40649. ], FreeCamera.prototype, "checkCollisions", void 0);
  40650. __decorate([
  40651. BABYLON.serialize()
  40652. ], FreeCamera.prototype, "applyGravity", void 0);
  40653. return FreeCamera;
  40654. }(BABYLON.TargetCamera));
  40655. BABYLON.FreeCamera = FreeCamera;
  40656. })(BABYLON || (BABYLON = {}));
  40657. //# sourceMappingURL=babylon.freeCamera.js.map
  40658. var BABYLON;
  40659. (function (BABYLON) {
  40660. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  40661. function ArcRotateCameraKeyboardMoveInput() {
  40662. this._keys = new Array();
  40663. this.keysUp = [38];
  40664. this.keysDown = [40];
  40665. this.keysLeft = [37];
  40666. this.keysRight = [39];
  40667. this.keysReset = [220];
  40668. this.panningSensibility = 50.0;
  40669. this.zoomingSensibility = 25.0;
  40670. this.useAltToZoom = true;
  40671. }
  40672. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40673. var _this = this;
  40674. if (this._onCanvasBlurObserver) {
  40675. return;
  40676. }
  40677. this._scene = this.camera.getScene();
  40678. this._engine = this._scene.getEngine();
  40679. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40680. _this._keys = [];
  40681. });
  40682. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40683. var evt = info.event;
  40684. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40685. _this._ctrlPressed = evt.ctrlKey;
  40686. _this._altPressed = evt.altKey;
  40687. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40688. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40689. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40690. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40691. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40692. var index = _this._keys.indexOf(evt.keyCode);
  40693. if (index === -1) {
  40694. _this._keys.push(evt.keyCode);
  40695. }
  40696. if (evt.preventDefault) {
  40697. if (!noPreventDefault) {
  40698. evt.preventDefault();
  40699. }
  40700. }
  40701. }
  40702. }
  40703. else {
  40704. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40705. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40706. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40707. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40708. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40709. var index = _this._keys.indexOf(evt.keyCode);
  40710. if (index >= 0) {
  40711. _this._keys.splice(index, 1);
  40712. }
  40713. if (evt.preventDefault) {
  40714. if (!noPreventDefault) {
  40715. evt.preventDefault();
  40716. }
  40717. }
  40718. }
  40719. }
  40720. });
  40721. };
  40722. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40723. if (this._scene) {
  40724. if (this._onKeyboardObserver) {
  40725. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40726. }
  40727. if (this._onCanvasBlurObserver) {
  40728. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40729. }
  40730. this._onKeyboardObserver = null;
  40731. this._onCanvasBlurObserver = null;
  40732. }
  40733. this._keys = [];
  40734. };
  40735. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40736. if (this._onKeyboardObserver) {
  40737. var camera = this.camera;
  40738. for (var index = 0; index < this._keys.length; index++) {
  40739. var keyCode = this._keys[index];
  40740. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40741. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40742. camera.inertialPanningX -= 1 / this.panningSensibility;
  40743. }
  40744. else {
  40745. camera.inertialAlphaOffset -= 0.01;
  40746. }
  40747. }
  40748. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40749. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40750. camera.inertialPanningY += 1 / this.panningSensibility;
  40751. }
  40752. else if (this._altPressed && this.useAltToZoom) {
  40753. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  40754. }
  40755. else {
  40756. camera.inertialBetaOffset -= 0.01;
  40757. }
  40758. }
  40759. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40760. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40761. camera.inertialPanningX += 1 / this.panningSensibility;
  40762. }
  40763. else {
  40764. camera.inertialAlphaOffset += 0.01;
  40765. }
  40766. }
  40767. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40768. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40769. camera.inertialPanningY -= 1 / this.panningSensibility;
  40770. }
  40771. else if (this._altPressed && this.useAltToZoom) {
  40772. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  40773. }
  40774. else {
  40775. camera.inertialBetaOffset += 0.01;
  40776. }
  40777. }
  40778. else if (this.keysReset.indexOf(keyCode) !== -1) {
  40779. camera.restoreState();
  40780. }
  40781. }
  40782. }
  40783. };
  40784. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  40785. return "ArcRotateCameraKeyboardMoveInput";
  40786. };
  40787. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40788. return "keyboard";
  40789. };
  40790. __decorate([
  40791. BABYLON.serialize()
  40792. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40793. __decorate([
  40794. BABYLON.serialize()
  40795. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40796. __decorate([
  40797. BABYLON.serialize()
  40798. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40799. __decorate([
  40800. BABYLON.serialize()
  40801. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40802. __decorate([
  40803. BABYLON.serialize()
  40804. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  40805. __decorate([
  40806. BABYLON.serialize()
  40807. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  40808. __decorate([
  40809. BABYLON.serialize()
  40810. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  40811. __decorate([
  40812. BABYLON.serialize()
  40813. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  40814. return ArcRotateCameraKeyboardMoveInput;
  40815. }());
  40816. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  40817. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  40818. })(BABYLON || (BABYLON = {}));
  40819. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  40820. var BABYLON;
  40821. (function (BABYLON) {
  40822. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  40823. function ArcRotateCameraMouseWheelInput() {
  40824. this.wheelPrecision = 3.0;
  40825. /**
  40826. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  40827. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  40828. */
  40829. this.wheelDeltaPercentage = 0;
  40830. }
  40831. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  40832. var _this = this;
  40833. this._wheel = function (p, s) {
  40834. //sanity check - this should be a PointerWheel event.
  40835. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  40836. return;
  40837. var event = p.event;
  40838. var delta = 0;
  40839. if (event.wheelDelta) {
  40840. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  40841. }
  40842. else if (event.detail) {
  40843. delta = -event.detail / _this.wheelPrecision;
  40844. }
  40845. if (delta)
  40846. _this.camera.inertialRadiusOffset += delta;
  40847. if (event.preventDefault) {
  40848. if (!noPreventDefault) {
  40849. event.preventDefault();
  40850. }
  40851. }
  40852. };
  40853. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  40854. };
  40855. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  40856. if (this._observer && element) {
  40857. this.camera.getScene().onPointerObservable.remove(this._observer);
  40858. this._observer = null;
  40859. this._wheel = null;
  40860. }
  40861. };
  40862. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  40863. return "ArcRotateCameraMouseWheelInput";
  40864. };
  40865. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  40866. return "mousewheel";
  40867. };
  40868. __decorate([
  40869. BABYLON.serialize()
  40870. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  40871. __decorate([
  40872. BABYLON.serialize()
  40873. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  40874. return ArcRotateCameraMouseWheelInput;
  40875. }());
  40876. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  40877. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  40878. })(BABYLON || (BABYLON = {}));
  40879. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  40880. var BABYLON;
  40881. (function (BABYLON) {
  40882. var ArcRotateCameraPointersInput = /** @class */ (function () {
  40883. function ArcRotateCameraPointersInput() {
  40884. this.buttons = [0, 1, 2];
  40885. this.angularSensibilityX = 1000.0;
  40886. this.angularSensibilityY = 1000.0;
  40887. this.pinchPrecision = 12.0;
  40888. /**
  40889. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  40890. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  40891. */
  40892. this.pinchDeltaPercentage = 0;
  40893. this.panningSensibility = 1000.0;
  40894. this.multiTouchPanning = true;
  40895. this.multiTouchPanAndZoom = true;
  40896. this._isPanClick = false;
  40897. this.pinchInwards = true;
  40898. }
  40899. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  40900. var _this = this;
  40901. var engine = this.camera.getEngine();
  40902. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  40903. var pointA = null;
  40904. var pointB = null;
  40905. var previousPinchSquaredDistance = 0;
  40906. var initialDistance = 0;
  40907. var twoFingerActivityCount = 0;
  40908. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  40909. this._pointerInput = function (p, s) {
  40910. var evt = p.event;
  40911. var isTouch = p.event.pointerType === "touch";
  40912. if (engine.isInVRExclusivePointerMode) {
  40913. return;
  40914. }
  40915. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40916. return;
  40917. }
  40918. var srcElement = (evt.srcElement || evt.target);
  40919. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40920. try {
  40921. srcElement.setPointerCapture(evt.pointerId);
  40922. }
  40923. catch (e) {
  40924. //Nothing to do with the error. Execution will continue.
  40925. }
  40926. // Manage panning with pan button click
  40927. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  40928. // manage pointers
  40929. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  40930. if (pointA === null) {
  40931. pointA = cacheSoloPointer;
  40932. }
  40933. else if (pointB === null) {
  40934. pointB = cacheSoloPointer;
  40935. }
  40936. if (!noPreventDefault) {
  40937. evt.preventDefault();
  40938. element.focus();
  40939. }
  40940. }
  40941. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40942. _this.camera.restoreState();
  40943. }
  40944. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40945. try {
  40946. srcElement.releasePointerCapture(evt.pointerId);
  40947. }
  40948. catch (e) {
  40949. //Nothing to do with the error.
  40950. }
  40951. cacheSoloPointer = null;
  40952. previousPinchSquaredDistance = 0;
  40953. previousMultiTouchPanPosition.isPaning = false;
  40954. previousMultiTouchPanPosition.isPinching = false;
  40955. twoFingerActivityCount = 0;
  40956. initialDistance = 0;
  40957. if (!isTouch) {
  40958. pointB = null; // Mouse and pen are mono pointer
  40959. }
  40960. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40961. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40962. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40963. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40964. if (engine.badOS) {
  40965. pointA = pointB = null;
  40966. }
  40967. else {
  40968. //only remove the impacted pointer in case of multitouch allowing on most
  40969. //platforms switching from rotate to zoom and pan seamlessly.
  40970. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40971. pointA = pointB;
  40972. pointB = null;
  40973. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40974. }
  40975. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40976. pointB = null;
  40977. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40978. }
  40979. else {
  40980. pointA = pointB = null;
  40981. }
  40982. }
  40983. if (!noPreventDefault) {
  40984. evt.preventDefault();
  40985. }
  40986. }
  40987. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40988. if (!noPreventDefault) {
  40989. evt.preventDefault();
  40990. }
  40991. // One button down
  40992. if (pointA && pointB === null && cacheSoloPointer) {
  40993. if (_this.panningSensibility !== 0 &&
  40994. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40995. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40996. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40997. }
  40998. else {
  40999. var offsetX = evt.clientX - cacheSoloPointer.x;
  41000. var offsetY = evt.clientY - cacheSoloPointer.y;
  41001. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41002. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41003. }
  41004. cacheSoloPointer.x = evt.clientX;
  41005. cacheSoloPointer.y = evt.clientY;
  41006. }
  41007. else if (pointA && pointB) {
  41008. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41009. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41010. ed.x = evt.clientX;
  41011. ed.y = evt.clientY;
  41012. var direction = _this.pinchInwards ? 1 : -1;
  41013. var distX = pointA.x - pointB.x;
  41014. var distY = pointA.y - pointB.y;
  41015. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41016. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41017. if (previousPinchSquaredDistance === 0) {
  41018. initialDistance = pinchDistance;
  41019. previousPinchSquaredDistance = pinchSquaredDistance;
  41020. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41021. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41022. return;
  41023. }
  41024. if (_this.multiTouchPanAndZoom) {
  41025. if (_this.pinchDeltaPercentage) {
  41026. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41027. }
  41028. else {
  41029. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41030. (_this.pinchPrecision *
  41031. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41032. direction);
  41033. }
  41034. if (_this.panningSensibility !== 0) {
  41035. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41036. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41037. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41038. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41039. previousMultiTouchPanPosition.x = pointersCenterX;
  41040. previousMultiTouchPanPosition.y = pointersCenterY;
  41041. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41042. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41043. }
  41044. }
  41045. else {
  41046. twoFingerActivityCount++;
  41047. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41048. if (_this.pinchDeltaPercentage) {
  41049. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41050. }
  41051. else {
  41052. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41053. (_this.pinchPrecision *
  41054. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41055. direction);
  41056. }
  41057. previousMultiTouchPanPosition.isPaning = false;
  41058. previousMultiTouchPanPosition.isPinching = true;
  41059. }
  41060. else {
  41061. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41062. if (!previousMultiTouchPanPosition.isPaning) {
  41063. previousMultiTouchPanPosition.isPaning = true;
  41064. previousMultiTouchPanPosition.isPinching = false;
  41065. previousMultiTouchPanPosition.x = ed.x;
  41066. previousMultiTouchPanPosition.y = ed.y;
  41067. return;
  41068. }
  41069. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41070. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41071. }
  41072. }
  41073. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41074. previousMultiTouchPanPosition.x = ed.x;
  41075. previousMultiTouchPanPosition.y = ed.y;
  41076. }
  41077. }
  41078. previousPinchSquaredDistance = pinchSquaredDistance;
  41079. }
  41080. }
  41081. };
  41082. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41083. this._onContextMenu = function (evt) {
  41084. evt.preventDefault();
  41085. };
  41086. if (!this.camera._useCtrlForPanning) {
  41087. element.addEventListener("contextmenu", this._onContextMenu, false);
  41088. }
  41089. this._onLostFocus = function () {
  41090. //this._keys = [];
  41091. pointA = pointB = null;
  41092. previousPinchSquaredDistance = 0;
  41093. previousMultiTouchPanPosition.isPaning = false;
  41094. previousMultiTouchPanPosition.isPinching = false;
  41095. twoFingerActivityCount = 0;
  41096. cacheSoloPointer = null;
  41097. initialDistance = 0;
  41098. };
  41099. this._onMouseMove = function (evt) {
  41100. if (!engine.isPointerLock) {
  41101. return;
  41102. }
  41103. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41104. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41105. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41106. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41107. if (!noPreventDefault) {
  41108. evt.preventDefault();
  41109. }
  41110. };
  41111. this._onGestureStart = function (e) {
  41112. if (window.MSGesture === undefined) {
  41113. return;
  41114. }
  41115. if (!_this._MSGestureHandler) {
  41116. _this._MSGestureHandler = new MSGesture();
  41117. _this._MSGestureHandler.target = element;
  41118. }
  41119. _this._MSGestureHandler.addPointer(e.pointerId);
  41120. };
  41121. this._onGesture = function (e) {
  41122. _this.camera.radius *= e.scale;
  41123. if (e.preventDefault) {
  41124. if (!noPreventDefault) {
  41125. e.stopPropagation();
  41126. e.preventDefault();
  41127. }
  41128. }
  41129. };
  41130. element.addEventListener("mousemove", this._onMouseMove, false);
  41131. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41132. element.addEventListener("MSGestureChange", this._onGesture, false);
  41133. BABYLON.Tools.RegisterTopRootEvents([
  41134. { name: "blur", handler: this._onLostFocus }
  41135. ]);
  41136. };
  41137. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41138. if (this._onLostFocus) {
  41139. BABYLON.Tools.UnregisterTopRootEvents([
  41140. { name: "blur", handler: this._onLostFocus }
  41141. ]);
  41142. }
  41143. if (element && this._observer) {
  41144. this.camera.getScene().onPointerObservable.remove(this._observer);
  41145. this._observer = null;
  41146. if (this._onContextMenu) {
  41147. element.removeEventListener("contextmenu", this._onContextMenu);
  41148. }
  41149. if (this._onMouseMove) {
  41150. element.removeEventListener("mousemove", this._onMouseMove);
  41151. }
  41152. if (this._onGestureStart) {
  41153. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41154. }
  41155. if (this._onGesture) {
  41156. element.removeEventListener("MSGestureChange", this._onGesture);
  41157. }
  41158. this._isPanClick = false;
  41159. this.pinchInwards = true;
  41160. this._onMouseMove = null;
  41161. this._onGestureStart = null;
  41162. this._onGesture = null;
  41163. this._MSGestureHandler = null;
  41164. this._onLostFocus = null;
  41165. this._onContextMenu = null;
  41166. }
  41167. };
  41168. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41169. return "ArcRotateCameraPointersInput";
  41170. };
  41171. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41172. return "pointers";
  41173. };
  41174. __decorate([
  41175. BABYLON.serialize()
  41176. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41177. __decorate([
  41178. BABYLON.serialize()
  41179. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41180. __decorate([
  41181. BABYLON.serialize()
  41182. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41183. __decorate([
  41184. BABYLON.serialize()
  41185. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41186. __decorate([
  41187. BABYLON.serialize()
  41188. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41189. __decorate([
  41190. BABYLON.serialize()
  41191. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41192. __decorate([
  41193. BABYLON.serialize()
  41194. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41195. __decorate([
  41196. BABYLON.serialize()
  41197. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41198. return ArcRotateCameraPointersInput;
  41199. }());
  41200. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41201. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41202. })(BABYLON || (BABYLON = {}));
  41203. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41204. var BABYLON;
  41205. (function (BABYLON) {
  41206. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41207. __extends(ArcRotateCameraInputsManager, _super);
  41208. function ArcRotateCameraInputsManager(camera) {
  41209. return _super.call(this, camera) || this;
  41210. }
  41211. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41212. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41213. return this;
  41214. };
  41215. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41216. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41217. return this;
  41218. };
  41219. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41220. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41221. return this;
  41222. };
  41223. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41224. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41225. return this;
  41226. };
  41227. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41228. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41229. return this;
  41230. };
  41231. return ArcRotateCameraInputsManager;
  41232. }(BABYLON.CameraInputsManager));
  41233. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41234. })(BABYLON || (BABYLON = {}));
  41235. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41236. var BABYLON;
  41237. (function (BABYLON) {
  41238. var ArcRotateCamera = /** @class */ (function (_super) {
  41239. __extends(ArcRotateCamera, _super);
  41240. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41241. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41242. _this.inertialAlphaOffset = 0;
  41243. _this.inertialBetaOffset = 0;
  41244. _this.inertialRadiusOffset = 0;
  41245. _this.lowerAlphaLimit = null;
  41246. _this.upperAlphaLimit = null;
  41247. _this.lowerBetaLimit = 0.01;
  41248. _this.upperBetaLimit = Math.PI;
  41249. _this.lowerRadiusLimit = null;
  41250. _this.upperRadiusLimit = null;
  41251. _this.inertialPanningX = 0;
  41252. _this.inertialPanningY = 0;
  41253. _this.pinchToPanMaxDistance = 20;
  41254. _this.panningDistanceLimit = null;
  41255. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41256. _this.panningInertia = 0.9;
  41257. //-- end properties for backward compatibility for inputs
  41258. _this.zoomOnFactor = 1;
  41259. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41260. _this.allowUpsideDown = true;
  41261. _this._viewMatrix = new BABYLON.Matrix();
  41262. // Panning
  41263. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41264. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41265. _this.checkCollisions = false;
  41266. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41267. _this._previousPosition = BABYLON.Vector3.Zero();
  41268. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41269. _this._newPosition = BABYLON.Vector3.Zero();
  41270. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41271. if (collidedMesh === void 0) { collidedMesh = null; }
  41272. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41273. newPosition.multiplyInPlace(_this._collider._radius);
  41274. }
  41275. if (!collidedMesh) {
  41276. _this._previousPosition.copyFrom(_this.position);
  41277. }
  41278. else {
  41279. _this.setPosition(newPosition);
  41280. if (_this.onCollide) {
  41281. _this.onCollide(collidedMesh);
  41282. }
  41283. }
  41284. // Recompute because of constraints
  41285. var cosa = Math.cos(_this.alpha);
  41286. var sina = Math.sin(_this.alpha);
  41287. var cosb = Math.cos(_this.beta);
  41288. var sinb = Math.sin(_this.beta);
  41289. if (sinb === 0) {
  41290. sinb = 0.0001;
  41291. }
  41292. var target = _this._getTargetPosition();
  41293. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41294. _this.position.copyFrom(_this._newPosition);
  41295. var up = _this.upVector;
  41296. if (_this.allowUpsideDown && _this.beta < 0) {
  41297. up = up.clone();
  41298. up = up.negate();
  41299. }
  41300. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41301. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41302. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41303. _this._collisionTriggered = false;
  41304. };
  41305. _this._target = BABYLON.Vector3.Zero();
  41306. if (target) {
  41307. _this.setTarget(target);
  41308. }
  41309. _this.alpha = alpha;
  41310. _this.beta = beta;
  41311. _this.radius = radius;
  41312. _this.getViewMatrix();
  41313. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41314. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41315. return _this;
  41316. }
  41317. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41318. get: function () {
  41319. return this._target;
  41320. },
  41321. set: function (value) {
  41322. this.setTarget(value);
  41323. },
  41324. enumerable: true,
  41325. configurable: true
  41326. });
  41327. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41328. //-- begin properties for backward compatibility for inputs
  41329. get: function () {
  41330. var pointers = this.inputs.attached["pointers"];
  41331. if (pointers)
  41332. return pointers.angularSensibilityX;
  41333. return 0;
  41334. },
  41335. set: function (value) {
  41336. var pointers = this.inputs.attached["pointers"];
  41337. if (pointers) {
  41338. pointers.angularSensibilityX = value;
  41339. }
  41340. },
  41341. enumerable: true,
  41342. configurable: true
  41343. });
  41344. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41345. get: function () {
  41346. var pointers = this.inputs.attached["pointers"];
  41347. if (pointers)
  41348. return pointers.angularSensibilityY;
  41349. return 0;
  41350. },
  41351. set: function (value) {
  41352. var pointers = this.inputs.attached["pointers"];
  41353. if (pointers) {
  41354. pointers.angularSensibilityY = value;
  41355. }
  41356. },
  41357. enumerable: true,
  41358. configurable: true
  41359. });
  41360. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41361. get: function () {
  41362. var pointers = this.inputs.attached["pointers"];
  41363. if (pointers)
  41364. return pointers.pinchPrecision;
  41365. return 0;
  41366. },
  41367. set: function (value) {
  41368. var pointers = this.inputs.attached["pointers"];
  41369. if (pointers) {
  41370. pointers.pinchPrecision = value;
  41371. }
  41372. },
  41373. enumerable: true,
  41374. configurable: true
  41375. });
  41376. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41377. get: function () {
  41378. var pointers = this.inputs.attached["pointers"];
  41379. if (pointers)
  41380. return pointers.pinchDeltaPercentage;
  41381. return 0;
  41382. },
  41383. set: function (value) {
  41384. var pointers = this.inputs.attached["pointers"];
  41385. if (pointers) {
  41386. pointers.pinchDeltaPercentage = value;
  41387. }
  41388. },
  41389. enumerable: true,
  41390. configurable: true
  41391. });
  41392. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41393. get: function () {
  41394. var pointers = this.inputs.attached["pointers"];
  41395. if (pointers)
  41396. return pointers.panningSensibility;
  41397. return 0;
  41398. },
  41399. set: function (value) {
  41400. var pointers = this.inputs.attached["pointers"];
  41401. if (pointers) {
  41402. pointers.panningSensibility = value;
  41403. }
  41404. },
  41405. enumerable: true,
  41406. configurable: true
  41407. });
  41408. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41409. get: function () {
  41410. var keyboard = this.inputs.attached["keyboard"];
  41411. if (keyboard)
  41412. return keyboard.keysUp;
  41413. return [];
  41414. },
  41415. set: function (value) {
  41416. var keyboard = this.inputs.attached["keyboard"];
  41417. if (keyboard)
  41418. keyboard.keysUp = value;
  41419. },
  41420. enumerable: true,
  41421. configurable: true
  41422. });
  41423. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41424. get: function () {
  41425. var keyboard = this.inputs.attached["keyboard"];
  41426. if (keyboard)
  41427. return keyboard.keysDown;
  41428. return [];
  41429. },
  41430. set: function (value) {
  41431. var keyboard = this.inputs.attached["keyboard"];
  41432. if (keyboard)
  41433. keyboard.keysDown = value;
  41434. },
  41435. enumerable: true,
  41436. configurable: true
  41437. });
  41438. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41439. get: function () {
  41440. var keyboard = this.inputs.attached["keyboard"];
  41441. if (keyboard)
  41442. return keyboard.keysLeft;
  41443. return [];
  41444. },
  41445. set: function (value) {
  41446. var keyboard = this.inputs.attached["keyboard"];
  41447. if (keyboard)
  41448. keyboard.keysLeft = value;
  41449. },
  41450. enumerable: true,
  41451. configurable: true
  41452. });
  41453. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41454. get: function () {
  41455. var keyboard = this.inputs.attached["keyboard"];
  41456. if (keyboard)
  41457. return keyboard.keysRight;
  41458. return [];
  41459. },
  41460. set: function (value) {
  41461. var keyboard = this.inputs.attached["keyboard"];
  41462. if (keyboard)
  41463. keyboard.keysRight = value;
  41464. },
  41465. enumerable: true,
  41466. configurable: true
  41467. });
  41468. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  41469. get: function () {
  41470. var mousewheel = this.inputs.attached["mousewheel"];
  41471. if (mousewheel)
  41472. return mousewheel.wheelPrecision;
  41473. return 0;
  41474. },
  41475. set: function (value) {
  41476. var mousewheel = this.inputs.attached["mousewheel"];
  41477. if (mousewheel)
  41478. mousewheel.wheelPrecision = value;
  41479. },
  41480. enumerable: true,
  41481. configurable: true
  41482. });
  41483. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  41484. get: function () {
  41485. var mousewheel = this.inputs.attached["mousewheel"];
  41486. if (mousewheel)
  41487. return mousewheel.wheelDeltaPercentage;
  41488. return 0;
  41489. },
  41490. set: function (value) {
  41491. var mousewheel = this.inputs.attached["mousewheel"];
  41492. if (mousewheel)
  41493. mousewheel.wheelDeltaPercentage = value;
  41494. },
  41495. enumerable: true,
  41496. configurable: true
  41497. });
  41498. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  41499. get: function () {
  41500. return this._bouncingBehavior;
  41501. },
  41502. enumerable: true,
  41503. configurable: true
  41504. });
  41505. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  41506. get: function () {
  41507. return this._bouncingBehavior != null;
  41508. },
  41509. set: function (value) {
  41510. if (value === this.useBouncingBehavior) {
  41511. return;
  41512. }
  41513. if (value) {
  41514. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  41515. this.addBehavior(this._bouncingBehavior);
  41516. }
  41517. else if (this._bouncingBehavior) {
  41518. this.removeBehavior(this._bouncingBehavior);
  41519. this._bouncingBehavior = null;
  41520. }
  41521. },
  41522. enumerable: true,
  41523. configurable: true
  41524. });
  41525. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  41526. get: function () {
  41527. return this._framingBehavior;
  41528. },
  41529. enumerable: true,
  41530. configurable: true
  41531. });
  41532. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  41533. get: function () {
  41534. return this._framingBehavior != null;
  41535. },
  41536. set: function (value) {
  41537. if (value === this.useFramingBehavior) {
  41538. return;
  41539. }
  41540. if (value) {
  41541. this._framingBehavior = new BABYLON.FramingBehavior();
  41542. this.addBehavior(this._framingBehavior);
  41543. }
  41544. else if (this._framingBehavior) {
  41545. this.removeBehavior(this._framingBehavior);
  41546. this._framingBehavior = null;
  41547. }
  41548. },
  41549. enumerable: true,
  41550. configurable: true
  41551. });
  41552. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  41553. get: function () {
  41554. return this._autoRotationBehavior;
  41555. },
  41556. enumerable: true,
  41557. configurable: true
  41558. });
  41559. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  41560. get: function () {
  41561. return this._autoRotationBehavior != null;
  41562. },
  41563. set: function (value) {
  41564. if (value === this.useAutoRotationBehavior) {
  41565. return;
  41566. }
  41567. if (value) {
  41568. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  41569. this.addBehavior(this._autoRotationBehavior);
  41570. }
  41571. else if (this._autoRotationBehavior) {
  41572. this.removeBehavior(this._autoRotationBehavior);
  41573. this._autoRotationBehavior = null;
  41574. }
  41575. },
  41576. enumerable: true,
  41577. configurable: true
  41578. });
  41579. // Cache
  41580. ArcRotateCamera.prototype._initCache = function () {
  41581. _super.prototype._initCache.call(this);
  41582. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  41583. this._cache.alpha = undefined;
  41584. this._cache.beta = undefined;
  41585. this._cache.radius = undefined;
  41586. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  41587. };
  41588. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  41589. if (!ignoreParentClass) {
  41590. _super.prototype._updateCache.call(this);
  41591. }
  41592. this._cache._target.copyFrom(this._getTargetPosition());
  41593. this._cache.alpha = this.alpha;
  41594. this._cache.beta = this.beta;
  41595. this._cache.radius = this.radius;
  41596. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  41597. };
  41598. ArcRotateCamera.prototype._getTargetPosition = function () {
  41599. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  41600. var pos = this._targetHost.getAbsolutePosition();
  41601. if (this._targetBoundingCenter) {
  41602. pos.addToRef(this._targetBoundingCenter, this._target);
  41603. }
  41604. else {
  41605. this._target.copyFrom(pos);
  41606. }
  41607. }
  41608. var lockedTargetPosition = this._getLockedTargetPosition();
  41609. if (lockedTargetPosition) {
  41610. return lockedTargetPosition;
  41611. }
  41612. return this._target;
  41613. };
  41614. ArcRotateCamera.prototype.storeState = function () {
  41615. this._storedAlpha = this.alpha;
  41616. this._storedBeta = this.beta;
  41617. this._storedRadius = this.radius;
  41618. this._storedTarget = this._getTargetPosition().clone();
  41619. return _super.prototype.storeState.call(this);
  41620. };
  41621. /**
  41622. * Restored camera state. You must call storeState() first
  41623. */
  41624. ArcRotateCamera.prototype._restoreStateValues = function () {
  41625. if (!_super.prototype._restoreStateValues.call(this)) {
  41626. return false;
  41627. }
  41628. this.alpha = this._storedAlpha;
  41629. this.beta = this._storedBeta;
  41630. this.radius = this._storedRadius;
  41631. this.setTarget(this._storedTarget.clone());
  41632. this.inertialAlphaOffset = 0;
  41633. this.inertialBetaOffset = 0;
  41634. this.inertialRadiusOffset = 0;
  41635. this.inertialPanningX = 0;
  41636. this.inertialPanningY = 0;
  41637. return true;
  41638. };
  41639. // Synchronized
  41640. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  41641. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  41642. return false;
  41643. return this._cache._target.equals(this._getTargetPosition())
  41644. && this._cache.alpha === this.alpha
  41645. && this._cache.beta === this.beta
  41646. && this._cache.radius === this.radius
  41647. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  41648. };
  41649. // Methods
  41650. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  41651. var _this = this;
  41652. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  41653. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  41654. this._useCtrlForPanning = useCtrlForPanning;
  41655. this._panningMouseButton = panningMouseButton;
  41656. this.inputs.attachElement(element, noPreventDefault);
  41657. this._reset = function () {
  41658. _this.inertialAlphaOffset = 0;
  41659. _this.inertialBetaOffset = 0;
  41660. _this.inertialRadiusOffset = 0;
  41661. _this.inertialPanningX = 0;
  41662. _this.inertialPanningY = 0;
  41663. };
  41664. };
  41665. ArcRotateCamera.prototype.detachControl = function (element) {
  41666. this.inputs.detachElement(element);
  41667. if (this._reset) {
  41668. this._reset();
  41669. }
  41670. };
  41671. ArcRotateCamera.prototype._checkInputs = function () {
  41672. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  41673. if (this._collisionTriggered) {
  41674. return;
  41675. }
  41676. this.inputs.checkInputs();
  41677. // Inertia
  41678. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  41679. if (this.getScene().useRightHandedSystem) {
  41680. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41681. }
  41682. else {
  41683. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41684. }
  41685. this.beta += this.inertialBetaOffset;
  41686. this.radius -= this.inertialRadiusOffset;
  41687. this.inertialAlphaOffset *= this.inertia;
  41688. this.inertialBetaOffset *= this.inertia;
  41689. this.inertialRadiusOffset *= this.inertia;
  41690. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  41691. this.inertialAlphaOffset = 0;
  41692. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  41693. this.inertialBetaOffset = 0;
  41694. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  41695. this.inertialRadiusOffset = 0;
  41696. }
  41697. // Panning inertia
  41698. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  41699. if (!this._localDirection) {
  41700. this._localDirection = BABYLON.Vector3.Zero();
  41701. this._transformedDirection = BABYLON.Vector3.Zero();
  41702. }
  41703. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  41704. this._localDirection.multiplyInPlace(this.panningAxis);
  41705. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  41706. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  41707. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  41708. if (!this.panningAxis.y) {
  41709. this._transformedDirection.y = 0;
  41710. }
  41711. if (!this._targetHost) {
  41712. if (this.panningDistanceLimit) {
  41713. this._transformedDirection.addInPlace(this._target);
  41714. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  41715. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  41716. this._target.copyFrom(this._transformedDirection);
  41717. }
  41718. }
  41719. else {
  41720. this._target.addInPlace(this._transformedDirection);
  41721. }
  41722. }
  41723. this.inertialPanningX *= this.panningInertia;
  41724. this.inertialPanningY *= this.panningInertia;
  41725. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  41726. this.inertialPanningX = 0;
  41727. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  41728. this.inertialPanningY = 0;
  41729. }
  41730. // Limits
  41731. this._checkLimits();
  41732. _super.prototype._checkInputs.call(this);
  41733. };
  41734. ArcRotateCamera.prototype._checkLimits = function () {
  41735. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  41736. if (this.allowUpsideDown && this.beta > Math.PI) {
  41737. this.beta = this.beta - (2 * Math.PI);
  41738. }
  41739. }
  41740. else {
  41741. if (this.beta < this.lowerBetaLimit) {
  41742. this.beta = this.lowerBetaLimit;
  41743. }
  41744. }
  41745. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  41746. if (this.allowUpsideDown && this.beta < -Math.PI) {
  41747. this.beta = this.beta + (2 * Math.PI);
  41748. }
  41749. }
  41750. else {
  41751. if (this.beta > this.upperBetaLimit) {
  41752. this.beta = this.upperBetaLimit;
  41753. }
  41754. }
  41755. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  41756. this.alpha = this.lowerAlphaLimit;
  41757. }
  41758. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  41759. this.alpha = this.upperAlphaLimit;
  41760. }
  41761. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  41762. this.radius = this.lowerRadiusLimit;
  41763. }
  41764. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  41765. this.radius = this.upperRadiusLimit;
  41766. }
  41767. };
  41768. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  41769. var radiusv3 = this.position.subtract(this._getTargetPosition());
  41770. this.radius = radiusv3.length();
  41771. if (this.radius === 0) {
  41772. this.radius = 0.0001; // Just to avoid division by zero
  41773. }
  41774. // Alpha
  41775. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  41776. if (radiusv3.z < 0) {
  41777. this.alpha = 2 * Math.PI - this.alpha;
  41778. }
  41779. // Beta
  41780. this.beta = Math.acos(radiusv3.y / this.radius);
  41781. this._checkLimits();
  41782. };
  41783. ArcRotateCamera.prototype.setPosition = function (position) {
  41784. if (this.position.equals(position)) {
  41785. return;
  41786. }
  41787. this.position.copyFrom(position);
  41788. this.rebuildAnglesAndRadius();
  41789. };
  41790. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  41791. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  41792. if (allowSamePosition === void 0) { allowSamePosition = false; }
  41793. if (target.getBoundingInfo) {
  41794. if (toBoundingCenter) {
  41795. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  41796. }
  41797. else {
  41798. this._targetBoundingCenter = null;
  41799. }
  41800. this._targetHost = target;
  41801. this._target = this._getTargetPosition();
  41802. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  41803. }
  41804. else {
  41805. var newTarget = target;
  41806. var currentTarget = this._getTargetPosition();
  41807. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  41808. return;
  41809. }
  41810. this._targetHost = null;
  41811. this._target = newTarget;
  41812. this._targetBoundingCenter = null;
  41813. this.onMeshTargetChangedObservable.notifyObservers(null);
  41814. }
  41815. this.rebuildAnglesAndRadius();
  41816. };
  41817. ArcRotateCamera.prototype._getViewMatrix = function () {
  41818. // Compute
  41819. var cosa = Math.cos(this.alpha);
  41820. var sina = Math.sin(this.alpha);
  41821. var cosb = Math.cos(this.beta);
  41822. var sinb = Math.sin(this.beta);
  41823. if (sinb === 0) {
  41824. sinb = 0.0001;
  41825. }
  41826. var target = this._getTargetPosition();
  41827. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  41828. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  41829. if (!this._collider) {
  41830. this._collider = new BABYLON.Collider();
  41831. }
  41832. this._collider._radius = this.collisionRadius;
  41833. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  41834. this._collisionTriggered = true;
  41835. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  41836. }
  41837. else {
  41838. this.position.copyFrom(this._newPosition);
  41839. var up = this.upVector;
  41840. if (this.allowUpsideDown && sinb < 0) {
  41841. up = up.clone();
  41842. up = up.negate();
  41843. }
  41844. if (this.getScene().useRightHandedSystem) {
  41845. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  41846. }
  41847. else {
  41848. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  41849. }
  41850. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  41851. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  41852. }
  41853. this._currentTarget = target;
  41854. return this._viewMatrix;
  41855. };
  41856. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  41857. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41858. meshes = meshes || this.getScene().meshes;
  41859. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  41860. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  41861. this.radius = distance * this.zoomOnFactor;
  41862. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  41863. };
  41864. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  41865. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  41866. var meshesOrMinMaxVector;
  41867. var distance;
  41868. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  41869. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  41870. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  41871. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  41872. }
  41873. else {
  41874. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  41875. meshesOrMinMaxVector = minMaxVectorAndDistance;
  41876. distance = minMaxVectorAndDistance.distance;
  41877. }
  41878. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  41879. if (!doNotUpdateMaxZ) {
  41880. this.maxZ = distance * 2;
  41881. }
  41882. };
  41883. /**
  41884. * @override
  41885. * Override Camera.createRigCamera
  41886. */
  41887. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  41888. var alphaShift = 0;
  41889. switch (this.cameraRigMode) {
  41890. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41891. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41893. case BABYLON.Camera.RIG_MODE_VR:
  41894. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  41895. break;
  41896. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41897. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  41898. break;
  41899. }
  41900. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  41901. rigCam._cameraRigParams = {};
  41902. return rigCam;
  41903. };
  41904. /**
  41905. * @override
  41906. * Override Camera._updateRigCameras
  41907. */
  41908. ArcRotateCamera.prototype._updateRigCameras = function () {
  41909. var camLeft = this._rigCameras[0];
  41910. var camRight = this._rigCameras[1];
  41911. camLeft.beta = camRight.beta = this.beta;
  41912. camLeft.radius = camRight.radius = this.radius;
  41913. switch (this.cameraRigMode) {
  41914. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  41915. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  41916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41917. case BABYLON.Camera.RIG_MODE_VR:
  41918. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41919. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41920. break;
  41921. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41922. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41923. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41924. break;
  41925. }
  41926. _super.prototype._updateRigCameras.call(this);
  41927. };
  41928. ArcRotateCamera.prototype.dispose = function () {
  41929. this.inputs.clear();
  41930. _super.prototype.dispose.call(this);
  41931. };
  41932. ArcRotateCamera.prototype.getClassName = function () {
  41933. return "ArcRotateCamera";
  41934. };
  41935. __decorate([
  41936. BABYLON.serialize()
  41937. ], ArcRotateCamera.prototype, "alpha", void 0);
  41938. __decorate([
  41939. BABYLON.serialize()
  41940. ], ArcRotateCamera.prototype, "beta", void 0);
  41941. __decorate([
  41942. BABYLON.serialize()
  41943. ], ArcRotateCamera.prototype, "radius", void 0);
  41944. __decorate([
  41945. BABYLON.serializeAsVector3("target")
  41946. ], ArcRotateCamera.prototype, "_target", void 0);
  41947. __decorate([
  41948. BABYLON.serialize()
  41949. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41950. __decorate([
  41951. BABYLON.serialize()
  41952. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41953. __decorate([
  41954. BABYLON.serialize()
  41955. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41956. __decorate([
  41957. BABYLON.serialize()
  41958. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41959. __decorate([
  41960. BABYLON.serialize()
  41961. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41962. __decorate([
  41963. BABYLON.serialize()
  41964. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41965. __decorate([
  41966. BABYLON.serialize()
  41967. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41968. __decorate([
  41969. BABYLON.serialize()
  41970. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41971. __decorate([
  41972. BABYLON.serialize()
  41973. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41974. __decorate([
  41975. BABYLON.serialize()
  41976. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41977. __decorate([
  41978. BABYLON.serialize()
  41979. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41980. __decorate([
  41981. BABYLON.serialize()
  41982. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41983. __decorate([
  41984. BABYLON.serialize()
  41985. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41986. __decorate([
  41987. BABYLON.serializeAsVector3()
  41988. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41989. __decorate([
  41990. BABYLON.serialize()
  41991. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41992. __decorate([
  41993. BABYLON.serialize()
  41994. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41995. __decorate([
  41996. BABYLON.serialize()
  41997. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41998. return ArcRotateCamera;
  41999. }(BABYLON.TargetCamera));
  42000. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42001. })(BABYLON || (BABYLON = {}));
  42002. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42003. var BABYLON;
  42004. (function (BABYLON) {
  42005. var HemisphericLight = /** @class */ (function (_super) {
  42006. __extends(HemisphericLight, _super);
  42007. /**
  42008. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42009. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42010. * The HemisphericLight can't cast shadows.
  42011. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42012. */
  42013. function HemisphericLight(name, direction, scene) {
  42014. var _this = _super.call(this, name, scene) || this;
  42015. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42016. _this.direction = direction || BABYLON.Vector3.Up();
  42017. return _this;
  42018. }
  42019. HemisphericLight.prototype._buildUniformLayout = function () {
  42020. this._uniformBuffer.addUniform("vLightData", 4);
  42021. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42022. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42023. this._uniformBuffer.addUniform("vLightGround", 3);
  42024. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42025. this._uniformBuffer.addUniform("depthValues", 2);
  42026. this._uniformBuffer.create();
  42027. };
  42028. /**
  42029. * Returns the string "HemisphericLight".
  42030. */
  42031. HemisphericLight.prototype.getClassName = function () {
  42032. return "HemisphericLight";
  42033. };
  42034. /**
  42035. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42036. * Returns the updated direction.
  42037. */
  42038. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42039. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42040. return this.direction;
  42041. };
  42042. HemisphericLight.prototype.getShadowGenerator = function () {
  42043. return null;
  42044. };
  42045. /**
  42046. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42047. * Returns the HemisphericLight.
  42048. */
  42049. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42050. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42051. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42052. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42053. return this;
  42054. };
  42055. HemisphericLight.prototype._getWorldMatrix = function () {
  42056. if (!this._worldMatrix) {
  42057. this._worldMatrix = BABYLON.Matrix.Identity();
  42058. }
  42059. return this._worldMatrix;
  42060. };
  42061. /**
  42062. * Returns the integer 3.
  42063. */
  42064. HemisphericLight.prototype.getTypeID = function () {
  42065. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42066. };
  42067. __decorate([
  42068. BABYLON.serializeAsColor3()
  42069. ], HemisphericLight.prototype, "groundColor", void 0);
  42070. __decorate([
  42071. BABYLON.serializeAsVector3()
  42072. ], HemisphericLight.prototype, "direction", void 0);
  42073. return HemisphericLight;
  42074. }(BABYLON.Light));
  42075. BABYLON.HemisphericLight = HemisphericLight;
  42076. })(BABYLON || (BABYLON = {}));
  42077. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42078. var BABYLON;
  42079. (function (BABYLON) {
  42080. var ShadowLight = /** @class */ (function (_super) {
  42081. __extends(ShadowLight, _super);
  42082. function ShadowLight() {
  42083. var _this = _super !== null && _super.apply(this, arguments) || this;
  42084. _this._needProjectionMatrixCompute = true;
  42085. return _this;
  42086. }
  42087. Object.defineProperty(ShadowLight.prototype, "direction", {
  42088. get: function () {
  42089. return this._direction;
  42090. },
  42091. set: function (value) {
  42092. this._direction = value;
  42093. },
  42094. enumerable: true,
  42095. configurable: true
  42096. });
  42097. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42098. get: function () {
  42099. return this._shadowMinZ;
  42100. },
  42101. set: function (value) {
  42102. this._shadowMinZ = value;
  42103. this.forceProjectionMatrixCompute();
  42104. },
  42105. enumerable: true,
  42106. configurable: true
  42107. });
  42108. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42109. get: function () {
  42110. return this._shadowMaxZ;
  42111. },
  42112. set: function (value) {
  42113. this._shadowMaxZ = value;
  42114. this.forceProjectionMatrixCompute();
  42115. },
  42116. enumerable: true,
  42117. configurable: true
  42118. });
  42119. /**
  42120. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  42121. */
  42122. ShadowLight.prototype.computeTransformedInformation = function () {
  42123. if (this.parent && this.parent.getWorldMatrix) {
  42124. if (!this.transformedPosition) {
  42125. this.transformedPosition = BABYLON.Vector3.Zero();
  42126. }
  42127. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42128. // In case the direction is present.
  42129. if (this.direction) {
  42130. if (!this.transformedDirection) {
  42131. this.transformedDirection = BABYLON.Vector3.Zero();
  42132. }
  42133. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42134. }
  42135. return true;
  42136. }
  42137. return false;
  42138. };
  42139. /**
  42140. * Return the depth scale used for the shadow map.
  42141. */
  42142. ShadowLight.prototype.getDepthScale = function () {
  42143. return 50.0;
  42144. };
  42145. /**
  42146. * Returns the light direction (Vector3) for any passed face index.
  42147. */
  42148. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42149. return this.transformedDirection ? this.transformedDirection : this.direction;
  42150. };
  42151. /**
  42152. * Returns the ShadowLight absolute position in the World.
  42153. */
  42154. ShadowLight.prototype.getAbsolutePosition = function () {
  42155. return this.transformedPosition ? this.transformedPosition : this.position;
  42156. };
  42157. /**
  42158. * Sets the ShadowLight direction toward the passed target (Vector3).
  42159. * Returns the updated ShadowLight direction (Vector3).
  42160. */
  42161. ShadowLight.prototype.setDirectionToTarget = function (target) {
  42162. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  42163. return this.direction;
  42164. };
  42165. /**
  42166. * Returns the light rotation (Vector3).
  42167. */
  42168. ShadowLight.prototype.getRotation = function () {
  42169. this.direction.normalize();
  42170. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  42171. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  42172. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  42173. };
  42174. /**
  42175. * Boolean : false by default.
  42176. */
  42177. ShadowLight.prototype.needCube = function () {
  42178. return false;
  42179. };
  42180. /**
  42181. * Specifies wether or not the projection matrix should be recomputed this frame.
  42182. */
  42183. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  42184. return this._needProjectionMatrixCompute;
  42185. };
  42186. /**
  42187. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  42188. */
  42189. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  42190. this._needProjectionMatrixCompute = true;
  42191. };
  42192. /**
  42193. * Get the world matrix of the sahdow lights.
  42194. */
  42195. ShadowLight.prototype._getWorldMatrix = function () {
  42196. if (!this._worldMatrix) {
  42197. this._worldMatrix = BABYLON.Matrix.Identity();
  42198. }
  42199. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42200. return this._worldMatrix;
  42201. };
  42202. /**
  42203. * Gets the minZ used for shadow according to both the scene and the light.
  42204. * @param activeCamera
  42205. */
  42206. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42207. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42208. };
  42209. /**
  42210. * Gets the maxZ used for shadow according to both the scene and the light.
  42211. * @param activeCamera
  42212. */
  42213. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42214. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42215. };
  42216. /**
  42217. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42218. * Returns the light.
  42219. */
  42220. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42221. if (this.customProjectionMatrixBuilder) {
  42222. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42223. }
  42224. else {
  42225. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42226. }
  42227. return this;
  42228. };
  42229. __decorate([
  42230. BABYLON.serializeAsVector3()
  42231. ], ShadowLight.prototype, "position", void 0);
  42232. __decorate([
  42233. BABYLON.serializeAsVector3()
  42234. ], ShadowLight.prototype, "direction", null);
  42235. __decorate([
  42236. BABYLON.serialize()
  42237. ], ShadowLight.prototype, "shadowMinZ", null);
  42238. __decorate([
  42239. BABYLON.serialize()
  42240. ], ShadowLight.prototype, "shadowMaxZ", null);
  42241. return ShadowLight;
  42242. }(BABYLON.Light));
  42243. BABYLON.ShadowLight = ShadowLight;
  42244. })(BABYLON || (BABYLON = {}));
  42245. //# sourceMappingURL=babylon.shadowLight.js.map
  42246. var BABYLON;
  42247. (function (BABYLON) {
  42248. var PointLight = /** @class */ (function (_super) {
  42249. __extends(PointLight, _super);
  42250. /**
  42251. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42252. * A PointLight emits the light in every direction.
  42253. * It can cast shadows.
  42254. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42255. * ```javascript
  42256. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42257. * ```
  42258. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42259. */
  42260. function PointLight(name, position, scene) {
  42261. var _this = _super.call(this, name, scene) || this;
  42262. _this._shadowAngle = Math.PI / 2;
  42263. _this.position = position;
  42264. return _this;
  42265. }
  42266. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42267. /**
  42268. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42269. * This specifies what angle the shadow will use to be created.
  42270. *
  42271. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42272. */
  42273. get: function () {
  42274. return this._shadowAngle;
  42275. },
  42276. /**
  42277. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42278. * This specifies what angle the shadow will use to be created.
  42279. *
  42280. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42281. */
  42282. set: function (value) {
  42283. this._shadowAngle = value;
  42284. this.forceProjectionMatrixCompute();
  42285. },
  42286. enumerable: true,
  42287. configurable: true
  42288. });
  42289. Object.defineProperty(PointLight.prototype, "direction", {
  42290. get: function () {
  42291. return this._direction;
  42292. },
  42293. /**
  42294. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42295. */
  42296. set: function (value) {
  42297. var previousNeedCube = this.needCube();
  42298. this._direction = value;
  42299. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42300. this._shadowGenerator.recreateShadowMap();
  42301. }
  42302. },
  42303. enumerable: true,
  42304. configurable: true
  42305. });
  42306. /**
  42307. * Returns the string "PointLight"
  42308. */
  42309. PointLight.prototype.getClassName = function () {
  42310. return "PointLight";
  42311. };
  42312. /**
  42313. * Returns the integer 0.
  42314. */
  42315. PointLight.prototype.getTypeID = function () {
  42316. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42317. };
  42318. /**
  42319. * Specifies wether or not the shadowmap should be a cube texture.
  42320. */
  42321. PointLight.prototype.needCube = function () {
  42322. return !this.direction;
  42323. };
  42324. /**
  42325. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42326. */
  42327. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42328. if (this.direction) {
  42329. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42330. }
  42331. else {
  42332. switch (faceIndex) {
  42333. case 0:
  42334. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42335. case 1:
  42336. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42337. case 2:
  42338. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42339. case 3:
  42340. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42341. case 4:
  42342. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42343. case 5:
  42344. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42345. }
  42346. }
  42347. return BABYLON.Vector3.Zero();
  42348. };
  42349. /**
  42350. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42351. * - fov = PI / 2
  42352. * - aspect ratio : 1.0
  42353. * - z-near and far equal to the active camera minZ and maxZ.
  42354. * Returns the PointLight.
  42355. */
  42356. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42357. var activeCamera = this.getScene().activeCamera;
  42358. if (!activeCamera) {
  42359. return;
  42360. }
  42361. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42362. };
  42363. PointLight.prototype._buildUniformLayout = function () {
  42364. this._uniformBuffer.addUniform("vLightData", 4);
  42365. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42366. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42367. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42368. this._uniformBuffer.addUniform("depthValues", 2);
  42369. this._uniformBuffer.create();
  42370. };
  42371. /**
  42372. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42373. * Returns the PointLight.
  42374. */
  42375. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42376. if (this.computeTransformedInformation()) {
  42377. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42378. return this;
  42379. }
  42380. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42381. return this;
  42382. };
  42383. __decorate([
  42384. BABYLON.serialize()
  42385. ], PointLight.prototype, "shadowAngle", null);
  42386. return PointLight;
  42387. }(BABYLON.ShadowLight));
  42388. BABYLON.PointLight = PointLight;
  42389. })(BABYLON || (BABYLON = {}));
  42390. //# sourceMappingURL=babylon.pointLight.js.map
  42391. var BABYLON;
  42392. (function (BABYLON) {
  42393. var DirectionalLight = /** @class */ (function (_super) {
  42394. __extends(DirectionalLight, _super);
  42395. /**
  42396. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42397. * The directional light is emitted from everywhere in the given direction.
  42398. * It can cast shawdows.
  42399. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42400. */
  42401. function DirectionalLight(name, direction, scene) {
  42402. var _this = _super.call(this, name, scene) || this;
  42403. _this._shadowFrustumSize = 0;
  42404. _this._shadowOrthoScale = 0.5;
  42405. _this.autoUpdateExtends = true;
  42406. // Cache
  42407. _this._orthoLeft = Number.MAX_VALUE;
  42408. _this._orthoRight = Number.MIN_VALUE;
  42409. _this._orthoTop = Number.MIN_VALUE;
  42410. _this._orthoBottom = Number.MAX_VALUE;
  42411. _this.position = direction.scale(-1.0);
  42412. _this.direction = direction;
  42413. return _this;
  42414. }
  42415. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42416. /**
  42417. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42418. */
  42419. get: function () {
  42420. return this._shadowFrustumSize;
  42421. },
  42422. /**
  42423. * Specifies a fix frustum size for the shadow generation.
  42424. */
  42425. set: function (value) {
  42426. this._shadowFrustumSize = value;
  42427. this.forceProjectionMatrixCompute();
  42428. },
  42429. enumerable: true,
  42430. configurable: true
  42431. });
  42432. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42433. get: function () {
  42434. return this._shadowOrthoScale;
  42435. },
  42436. set: function (value) {
  42437. this._shadowOrthoScale = value;
  42438. this.forceProjectionMatrixCompute();
  42439. },
  42440. enumerable: true,
  42441. configurable: true
  42442. });
  42443. /**
  42444. * Returns the string "DirectionalLight".
  42445. */
  42446. DirectionalLight.prototype.getClassName = function () {
  42447. return "DirectionalLight";
  42448. };
  42449. /**
  42450. * Returns the integer 1.
  42451. */
  42452. DirectionalLight.prototype.getTypeID = function () {
  42453. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42454. };
  42455. /**
  42456. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42457. * Returns the DirectionalLight Shadow projection matrix.
  42458. */
  42459. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42460. if (this.shadowFrustumSize > 0) {
  42461. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  42462. }
  42463. else {
  42464. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42465. }
  42466. };
  42467. /**
  42468. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  42469. * Returns the DirectionalLight Shadow projection matrix.
  42470. */
  42471. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  42472. var activeCamera = this.getScene().activeCamera;
  42473. if (!activeCamera) {
  42474. return;
  42475. }
  42476. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  42477. };
  42478. /**
  42479. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  42480. * Returns the DirectionalLight Shadow projection matrix.
  42481. */
  42482. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42483. var activeCamera = this.getScene().activeCamera;
  42484. if (!activeCamera) {
  42485. return;
  42486. }
  42487. // Check extends
  42488. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  42489. var tempVector3 = BABYLON.Vector3.Zero();
  42490. this._orthoLeft = Number.MAX_VALUE;
  42491. this._orthoRight = Number.MIN_VALUE;
  42492. this._orthoTop = Number.MIN_VALUE;
  42493. this._orthoBottom = Number.MAX_VALUE;
  42494. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  42495. var mesh = renderList[meshIndex];
  42496. if (!mesh) {
  42497. continue;
  42498. }
  42499. var boundingInfo = mesh.getBoundingInfo();
  42500. var boundingBox = boundingInfo.boundingBox;
  42501. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  42502. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  42503. if (tempVector3.x < this._orthoLeft)
  42504. this._orthoLeft = tempVector3.x;
  42505. if (tempVector3.y < this._orthoBottom)
  42506. this._orthoBottom = tempVector3.y;
  42507. if (tempVector3.x > this._orthoRight)
  42508. this._orthoRight = tempVector3.x;
  42509. if (tempVector3.y > this._orthoTop)
  42510. this._orthoTop = tempVector3.y;
  42511. }
  42512. }
  42513. }
  42514. var xOffset = this._orthoRight - this._orthoLeft;
  42515. var yOffset = this._orthoTop - this._orthoBottom;
  42516. 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);
  42517. };
  42518. DirectionalLight.prototype._buildUniformLayout = function () {
  42519. this._uniformBuffer.addUniform("vLightData", 4);
  42520. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42521. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42522. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42523. this._uniformBuffer.addUniform("depthValues", 2);
  42524. this._uniformBuffer.create();
  42525. };
  42526. /**
  42527. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  42528. * Returns the DirectionalLight.
  42529. */
  42530. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  42531. if (this.computeTransformedInformation()) {
  42532. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  42533. return this;
  42534. }
  42535. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  42536. return this;
  42537. };
  42538. /**
  42539. * Gets the minZ used for shadow according to both the scene and the light.
  42540. *
  42541. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42542. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42543. * @param activeCamera
  42544. */
  42545. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  42546. return 1;
  42547. };
  42548. /**
  42549. * Gets the maxZ used for shadow according to both the scene and the light.
  42550. *
  42551. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42552. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42553. * @param activeCamera
  42554. */
  42555. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  42556. return 1;
  42557. };
  42558. __decorate([
  42559. BABYLON.serialize()
  42560. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  42561. __decorate([
  42562. BABYLON.serialize()
  42563. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  42564. __decorate([
  42565. BABYLON.serialize()
  42566. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  42567. return DirectionalLight;
  42568. }(BABYLON.ShadowLight));
  42569. BABYLON.DirectionalLight = DirectionalLight;
  42570. })(BABYLON || (BABYLON = {}));
  42571. //# sourceMappingURL=babylon.directionalLight.js.map
  42572. var BABYLON;
  42573. (function (BABYLON) {
  42574. var SpotLight = /** @class */ (function (_super) {
  42575. __extends(SpotLight, _super);
  42576. /**
  42577. * Creates a SpotLight object in the scene with the passed parameters :
  42578. * - `position` (Vector3) is the initial SpotLight position,
  42579. * - `direction` (Vector3) is the initial SpotLight direction,
  42580. * - `angle` (float, in radians) is the spot light cone angle,
  42581. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  42582. * A spot light is a simply light oriented cone.
  42583. * It can cast shadows.
  42584. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42585. */
  42586. function SpotLight(name, position, direction, angle, exponent, scene) {
  42587. var _this = _super.call(this, name, scene) || this;
  42588. _this.position = position;
  42589. _this.direction = direction;
  42590. _this.angle = angle;
  42591. _this.exponent = exponent;
  42592. return _this;
  42593. }
  42594. Object.defineProperty(SpotLight.prototype, "angle", {
  42595. get: function () {
  42596. return this._angle;
  42597. },
  42598. set: function (value) {
  42599. this._angle = value;
  42600. this.forceProjectionMatrixCompute();
  42601. },
  42602. enumerable: true,
  42603. configurable: true
  42604. });
  42605. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  42606. get: function () {
  42607. return this._shadowAngleScale;
  42608. },
  42609. /**
  42610. * Allows scaling the angle of the light for shadow generation only.
  42611. */
  42612. set: function (value) {
  42613. this._shadowAngleScale = value;
  42614. this.forceProjectionMatrixCompute();
  42615. },
  42616. enumerable: true,
  42617. configurable: true
  42618. });
  42619. /**
  42620. * Returns the string "SpotLight".
  42621. */
  42622. SpotLight.prototype.getClassName = function () {
  42623. return "SpotLight";
  42624. };
  42625. /**
  42626. * Returns the integer 2.
  42627. */
  42628. SpotLight.prototype.getTypeID = function () {
  42629. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  42630. };
  42631. /**
  42632. * 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.
  42633. * Returns the SpotLight.
  42634. */
  42635. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42636. var activeCamera = this.getScene().activeCamera;
  42637. if (!activeCamera) {
  42638. return;
  42639. }
  42640. this._shadowAngleScale = this._shadowAngleScale || 1;
  42641. var angle = this._shadowAngleScale * this._angle;
  42642. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42643. };
  42644. SpotLight.prototype._buildUniformLayout = function () {
  42645. this._uniformBuffer.addUniform("vLightData", 4);
  42646. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42647. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42648. this._uniformBuffer.addUniform("vLightDirection", 3);
  42649. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42650. this._uniformBuffer.addUniform("depthValues", 2);
  42651. this._uniformBuffer.create();
  42652. };
  42653. /**
  42654. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  42655. * Return the SpotLight.
  42656. */
  42657. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  42658. var normalizeDirection;
  42659. if (this.computeTransformedInformation()) {
  42660. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  42661. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  42662. }
  42663. else {
  42664. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  42665. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42666. }
  42667. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  42668. return this;
  42669. };
  42670. __decorate([
  42671. BABYLON.serialize()
  42672. ], SpotLight.prototype, "angle", null);
  42673. __decorate([
  42674. BABYLON.serialize()
  42675. /**
  42676. * Allows scaling the angle of the light for shadow generation only.
  42677. */
  42678. ], SpotLight.prototype, "shadowAngleScale", null);
  42679. __decorate([
  42680. BABYLON.serialize()
  42681. ], SpotLight.prototype, "exponent", void 0);
  42682. return SpotLight;
  42683. }(BABYLON.ShadowLight));
  42684. BABYLON.SpotLight = SpotLight;
  42685. })(BABYLON || (BABYLON = {}));
  42686. //# sourceMappingURL=babylon.spotLight.js.map
  42687. var BABYLON;
  42688. (function (BABYLON) {
  42689. var AnimationRange = /** @class */ (function () {
  42690. function AnimationRange(name, from, to) {
  42691. this.name = name;
  42692. this.from = from;
  42693. this.to = to;
  42694. }
  42695. AnimationRange.prototype.clone = function () {
  42696. return new AnimationRange(this.name, this.from, this.to);
  42697. };
  42698. return AnimationRange;
  42699. }());
  42700. BABYLON.AnimationRange = AnimationRange;
  42701. /**
  42702. * Composed of a frame, and an action function
  42703. */
  42704. var AnimationEvent = /** @class */ (function () {
  42705. function AnimationEvent(frame, action, onlyOnce) {
  42706. this.frame = frame;
  42707. this.action = action;
  42708. this.onlyOnce = onlyOnce;
  42709. this.isDone = false;
  42710. }
  42711. return AnimationEvent;
  42712. }());
  42713. BABYLON.AnimationEvent = AnimationEvent;
  42714. var PathCursor = /** @class */ (function () {
  42715. function PathCursor(path) {
  42716. this.path = path;
  42717. this._onchange = new Array();
  42718. this.value = 0;
  42719. this.animations = new Array();
  42720. }
  42721. PathCursor.prototype.getPoint = function () {
  42722. var point = this.path.getPointAtLengthPosition(this.value);
  42723. return new BABYLON.Vector3(point.x, 0, point.y);
  42724. };
  42725. PathCursor.prototype.moveAhead = function (step) {
  42726. if (step === void 0) { step = 0.002; }
  42727. this.move(step);
  42728. return this;
  42729. };
  42730. PathCursor.prototype.moveBack = function (step) {
  42731. if (step === void 0) { step = 0.002; }
  42732. this.move(-step);
  42733. return this;
  42734. };
  42735. PathCursor.prototype.move = function (step) {
  42736. if (Math.abs(step) > 1) {
  42737. throw "step size should be less than 1.";
  42738. }
  42739. this.value += step;
  42740. this.ensureLimits();
  42741. this.raiseOnChange();
  42742. return this;
  42743. };
  42744. PathCursor.prototype.ensureLimits = function () {
  42745. while (this.value > 1) {
  42746. this.value -= 1;
  42747. }
  42748. while (this.value < 0) {
  42749. this.value += 1;
  42750. }
  42751. return this;
  42752. };
  42753. // used by animation engine
  42754. PathCursor.prototype.raiseOnChange = function () {
  42755. var _this = this;
  42756. this._onchange.forEach(function (f) { return f(_this); });
  42757. return this;
  42758. };
  42759. PathCursor.prototype.onchange = function (f) {
  42760. this._onchange.push(f);
  42761. return this;
  42762. };
  42763. return PathCursor;
  42764. }());
  42765. BABYLON.PathCursor = PathCursor;
  42766. var AnimationKeyInterpolation;
  42767. (function (AnimationKeyInterpolation) {
  42768. /**
  42769. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  42770. */
  42771. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  42772. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  42773. var Animation = /** @class */ (function () {
  42774. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  42775. this.name = name;
  42776. this.targetProperty = targetProperty;
  42777. this.framePerSecond = framePerSecond;
  42778. this.dataType = dataType;
  42779. this.loopMode = loopMode;
  42780. this.enableBlending = enableBlending;
  42781. this._runtimeAnimations = new Array();
  42782. // The set of event that will be linked to this animation
  42783. this._events = new Array();
  42784. this.blendingSpeed = 0.01;
  42785. this._ranges = {};
  42786. this.targetPropertyPath = targetProperty.split(".");
  42787. this.dataType = dataType;
  42788. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  42789. }
  42790. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  42791. var dataType = undefined;
  42792. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  42793. dataType = Animation.ANIMATIONTYPE_FLOAT;
  42794. }
  42795. else if (from instanceof BABYLON.Quaternion) {
  42796. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  42797. }
  42798. else if (from instanceof BABYLON.Vector3) {
  42799. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  42800. }
  42801. else if (from instanceof BABYLON.Vector2) {
  42802. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  42803. }
  42804. else if (from instanceof BABYLON.Color3) {
  42805. dataType = Animation.ANIMATIONTYPE_COLOR3;
  42806. }
  42807. else if (from instanceof BABYLON.Size) {
  42808. dataType = Animation.ANIMATIONTYPE_SIZE;
  42809. }
  42810. if (dataType == undefined) {
  42811. return null;
  42812. }
  42813. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  42814. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  42815. animation.setKeys(keys);
  42816. if (easingFunction !== undefined) {
  42817. animation.setEasingFunction(easingFunction);
  42818. }
  42819. return animation;
  42820. };
  42821. /**
  42822. * Sets up an animation.
  42823. * @param property the property to animate
  42824. * @param animationType the animation type to apply
  42825. * @param easingFunction the easing function used in the animation
  42826. * @returns The created animation
  42827. */
  42828. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  42829. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  42830. animation.setEasingFunction(easingFunction);
  42831. return animation;
  42832. };
  42833. /**
  42834. * Create and start an animation on a node
  42835. * @param {string} name defines the name of the global animation that will be run on all nodes
  42836. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42837. * @param {string} targetProperty defines property to animate
  42838. * @param {number} framePerSecond defines the number of frame per second yo use
  42839. * @param {number} totalFrame defines the number of frames in total
  42840. * @param {any} from defines the initial value
  42841. * @param {any} to defines the final value
  42842. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42843. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42844. * @param onAnimationEnd defines the callback to call when animation end
  42845. * @returns the animatable created for this animation
  42846. */
  42847. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42848. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42849. if (!animation) {
  42850. return null;
  42851. }
  42852. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42853. };
  42854. /**
  42855. * Create and start an animation on a node and its descendants
  42856. * @param {string} name defines the name of the global animation that will be run on all nodes
  42857. * @param {BABYLON.Node} node defines the root node where the animation will take place
  42858. * @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.
  42859. * @param {string} targetProperty defines property to animate
  42860. * @param {number} framePerSecond defines the number of frame per second yo use
  42861. * @param {number} totalFrame defines the number of frames in total
  42862. * @param {any} from defines the initial value
  42863. * @param {any} to defines the final value
  42864. * @param {number} loopMode defines which loop mode you want to use (off by default)
  42865. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  42866. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  42867. * @returns the list of animatables created for all nodes
  42868. * @example https://www.babylonjs-playground.com/#MH0VLI
  42869. */
  42870. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42871. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42872. if (!animation) {
  42873. return null;
  42874. }
  42875. var scene = node.getScene();
  42876. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42877. };
  42878. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  42879. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  42880. if (!animation) {
  42881. return null;
  42882. }
  42883. node.animations.push(animation);
  42884. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  42885. };
  42886. /**
  42887. * Transition property of the Camera to the target Value.
  42888. * @param property The property to transition
  42889. * @param targetValue The target Value of the property
  42890. * @param host The object where the property to animate belongs
  42891. * @param scene Scene used to run the animation
  42892. * @param frameRate Framerate (in frame/s) to use
  42893. * @param transition The transition type we want to use
  42894. * @param duration The duration of the animation, in milliseconds
  42895. * @param onAnimationEnd Call back trigger at the end of the animation.
  42896. */
  42897. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  42898. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  42899. if (duration <= 0) {
  42900. host[property] = targetValue;
  42901. if (onAnimationEnd) {
  42902. onAnimationEnd();
  42903. }
  42904. return null;
  42905. }
  42906. var endFrame = frameRate * (duration / 1000);
  42907. transition.setKeys([{
  42908. frame: 0,
  42909. value: host[property].clone ? host[property].clone() : host[property]
  42910. },
  42911. {
  42912. frame: endFrame,
  42913. value: targetValue
  42914. }]);
  42915. if (!host.animations) {
  42916. host.animations = [];
  42917. }
  42918. host.animations.push(transition);
  42919. var animation = scene.beginAnimation(host, 0, endFrame, false);
  42920. animation.onAnimationEnd = onAnimationEnd;
  42921. return animation;
  42922. };
  42923. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  42924. /**
  42925. * Return the array of runtime animations currently using this animation
  42926. */
  42927. get: function () {
  42928. return this._runtimeAnimations;
  42929. },
  42930. enumerable: true,
  42931. configurable: true
  42932. });
  42933. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42934. get: function () {
  42935. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42936. var runtimeAnimation = _a[_i];
  42937. if (!runtimeAnimation.isStopped) {
  42938. return true;
  42939. }
  42940. }
  42941. return false;
  42942. },
  42943. enumerable: true,
  42944. configurable: true
  42945. });
  42946. // Methods
  42947. /**
  42948. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42949. */
  42950. Animation.prototype.toString = function (fullDetails) {
  42951. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42952. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42953. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42954. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42955. if (fullDetails) {
  42956. ret += ", Ranges: {";
  42957. var first = true;
  42958. for (var name in this._ranges) {
  42959. if (first) {
  42960. ret += ", ";
  42961. first = false;
  42962. }
  42963. ret += name;
  42964. }
  42965. ret += "}";
  42966. }
  42967. return ret;
  42968. };
  42969. /**
  42970. * Add an event to this animation.
  42971. */
  42972. Animation.prototype.addEvent = function (event) {
  42973. this._events.push(event);
  42974. };
  42975. /**
  42976. * Remove all events found at the given frame
  42977. * @param frame
  42978. */
  42979. Animation.prototype.removeEvents = function (frame) {
  42980. for (var index = 0; index < this._events.length; index++) {
  42981. if (this._events[index].frame === frame) {
  42982. this._events.splice(index, 1);
  42983. index--;
  42984. }
  42985. }
  42986. };
  42987. Animation.prototype.getEvents = function () {
  42988. return this._events;
  42989. };
  42990. Animation.prototype.createRange = function (name, from, to) {
  42991. // check name not already in use; could happen for bones after serialized
  42992. if (!this._ranges[name]) {
  42993. this._ranges[name] = new AnimationRange(name, from, to);
  42994. }
  42995. };
  42996. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42997. if (deleteFrames === void 0) { deleteFrames = true; }
  42998. var range = this._ranges[name];
  42999. if (!range) {
  43000. return;
  43001. }
  43002. if (deleteFrames) {
  43003. var from = range.from;
  43004. var to = range.to;
  43005. // this loop MUST go high to low for multiple splices to work
  43006. for (var key = this._keys.length - 1; key >= 0; key--) {
  43007. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  43008. this._keys.splice(key, 1);
  43009. }
  43010. }
  43011. }
  43012. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  43013. };
  43014. Animation.prototype.getRange = function (name) {
  43015. return this._ranges[name];
  43016. };
  43017. Animation.prototype.getKeys = function () {
  43018. return this._keys;
  43019. };
  43020. Animation.prototype.getHighestFrame = function () {
  43021. var ret = 0;
  43022. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  43023. if (ret < this._keys[key].frame) {
  43024. ret = this._keys[key].frame;
  43025. }
  43026. }
  43027. return ret;
  43028. };
  43029. Animation.prototype.getEasingFunction = function () {
  43030. return this._easingFunction;
  43031. };
  43032. Animation.prototype.setEasingFunction = function (easingFunction) {
  43033. this._easingFunction = easingFunction;
  43034. };
  43035. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  43036. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  43037. };
  43038. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43039. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43040. };
  43041. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  43042. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  43043. };
  43044. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43045. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  43046. };
  43047. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  43048. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  43049. };
  43050. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43051. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43052. };
  43053. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  43054. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  43055. };
  43056. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43057. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43058. };
  43059. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  43060. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  43061. };
  43062. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  43063. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  43064. };
  43065. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  43066. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  43067. };
  43068. Animation.prototype.clone = function () {
  43069. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  43070. clone.enableBlending = this.enableBlending;
  43071. clone.blendingSpeed = this.blendingSpeed;
  43072. if (this._keys) {
  43073. clone.setKeys(this._keys);
  43074. }
  43075. if (this._ranges) {
  43076. clone._ranges = {};
  43077. for (var name in this._ranges) {
  43078. var range = this._ranges[name];
  43079. if (!range) {
  43080. continue;
  43081. }
  43082. clone._ranges[name] = range.clone();
  43083. }
  43084. }
  43085. return clone;
  43086. };
  43087. Animation.prototype.setKeys = function (values) {
  43088. this._keys = values.slice(0);
  43089. };
  43090. Animation.prototype.serialize = function () {
  43091. var serializationObject = {};
  43092. serializationObject.name = this.name;
  43093. serializationObject.property = this.targetProperty;
  43094. serializationObject.framePerSecond = this.framePerSecond;
  43095. serializationObject.dataType = this.dataType;
  43096. serializationObject.loopBehavior = this.loopMode;
  43097. serializationObject.enableBlending = this.enableBlending;
  43098. serializationObject.blendingSpeed = this.blendingSpeed;
  43099. var dataType = this.dataType;
  43100. serializationObject.keys = [];
  43101. var keys = this.getKeys();
  43102. for (var index = 0; index < keys.length; index++) {
  43103. var animationKey = keys[index];
  43104. var key = {};
  43105. key.frame = animationKey.frame;
  43106. switch (dataType) {
  43107. case Animation.ANIMATIONTYPE_FLOAT:
  43108. key.values = [animationKey.value];
  43109. break;
  43110. case Animation.ANIMATIONTYPE_QUATERNION:
  43111. case Animation.ANIMATIONTYPE_MATRIX:
  43112. case Animation.ANIMATIONTYPE_VECTOR3:
  43113. case Animation.ANIMATIONTYPE_COLOR3:
  43114. key.values = animationKey.value.asArray();
  43115. break;
  43116. }
  43117. serializationObject.keys.push(key);
  43118. }
  43119. serializationObject.ranges = [];
  43120. for (var name in this._ranges) {
  43121. var source = this._ranges[name];
  43122. if (!source) {
  43123. continue;
  43124. }
  43125. var range = {};
  43126. range.name = name;
  43127. range.from = source.from;
  43128. range.to = source.to;
  43129. serializationObject.ranges.push(range);
  43130. }
  43131. return serializationObject;
  43132. };
  43133. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  43134. get: function () {
  43135. return Animation._ANIMATIONTYPE_FLOAT;
  43136. },
  43137. enumerable: true,
  43138. configurable: true
  43139. });
  43140. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  43141. get: function () {
  43142. return Animation._ANIMATIONTYPE_VECTOR3;
  43143. },
  43144. enumerable: true,
  43145. configurable: true
  43146. });
  43147. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  43148. get: function () {
  43149. return Animation._ANIMATIONTYPE_VECTOR2;
  43150. },
  43151. enumerable: true,
  43152. configurable: true
  43153. });
  43154. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  43155. get: function () {
  43156. return Animation._ANIMATIONTYPE_SIZE;
  43157. },
  43158. enumerable: true,
  43159. configurable: true
  43160. });
  43161. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  43162. get: function () {
  43163. return Animation._ANIMATIONTYPE_QUATERNION;
  43164. },
  43165. enumerable: true,
  43166. configurable: true
  43167. });
  43168. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  43169. get: function () {
  43170. return Animation._ANIMATIONTYPE_MATRIX;
  43171. },
  43172. enumerable: true,
  43173. configurable: true
  43174. });
  43175. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  43176. get: function () {
  43177. return Animation._ANIMATIONTYPE_COLOR3;
  43178. },
  43179. enumerable: true,
  43180. configurable: true
  43181. });
  43182. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  43183. get: function () {
  43184. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  43185. },
  43186. enumerable: true,
  43187. configurable: true
  43188. });
  43189. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  43190. get: function () {
  43191. return Animation._ANIMATIONLOOPMODE_CYCLE;
  43192. },
  43193. enumerable: true,
  43194. configurable: true
  43195. });
  43196. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  43197. get: function () {
  43198. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43199. },
  43200. enumerable: true,
  43201. configurable: true
  43202. });
  43203. Animation.Parse = function (parsedAnimation) {
  43204. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43205. var dataType = parsedAnimation.dataType;
  43206. var keys = [];
  43207. var data;
  43208. var index;
  43209. if (parsedAnimation.enableBlending) {
  43210. animation.enableBlending = parsedAnimation.enableBlending;
  43211. }
  43212. if (parsedAnimation.blendingSpeed) {
  43213. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43214. }
  43215. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43216. var key = parsedAnimation.keys[index];
  43217. var inTangent;
  43218. var outTangent;
  43219. switch (dataType) {
  43220. case Animation.ANIMATIONTYPE_FLOAT:
  43221. data = key.values[0];
  43222. if (key.values.length >= 1) {
  43223. inTangent = key.values[1];
  43224. }
  43225. if (key.values.length >= 2) {
  43226. outTangent = key.values[2];
  43227. }
  43228. break;
  43229. case Animation.ANIMATIONTYPE_QUATERNION:
  43230. data = BABYLON.Quaternion.FromArray(key.values);
  43231. if (key.values.length >= 8) {
  43232. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43233. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43234. inTangent = _inTangent;
  43235. }
  43236. }
  43237. if (key.values.length >= 12) {
  43238. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43239. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43240. outTangent = _outTangent;
  43241. }
  43242. }
  43243. break;
  43244. case Animation.ANIMATIONTYPE_MATRIX:
  43245. data = BABYLON.Matrix.FromArray(key.values);
  43246. break;
  43247. case Animation.ANIMATIONTYPE_COLOR3:
  43248. data = BABYLON.Color3.FromArray(key.values);
  43249. break;
  43250. case Animation.ANIMATIONTYPE_VECTOR3:
  43251. default:
  43252. data = BABYLON.Vector3.FromArray(key.values);
  43253. break;
  43254. }
  43255. var keyData = {};
  43256. keyData.frame = key.frame;
  43257. keyData.value = data;
  43258. if (inTangent != undefined) {
  43259. keyData.inTangent = inTangent;
  43260. }
  43261. if (outTangent != undefined) {
  43262. keyData.outTangent = outTangent;
  43263. }
  43264. keys.push(keyData);
  43265. }
  43266. animation.setKeys(keys);
  43267. if (parsedAnimation.ranges) {
  43268. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43269. data = parsedAnimation.ranges[index];
  43270. animation.createRange(data.name, data.from, data.to);
  43271. }
  43272. }
  43273. return animation;
  43274. };
  43275. Animation.AppendSerializedAnimations = function (source, destination) {
  43276. if (source.animations) {
  43277. destination.animations = [];
  43278. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43279. var animation = source.animations[animationIndex];
  43280. destination.animations.push(animation.serialize());
  43281. }
  43282. }
  43283. };
  43284. Animation.AllowMatricesInterpolation = false;
  43285. // Statics
  43286. Animation._ANIMATIONTYPE_FLOAT = 0;
  43287. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43288. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43289. Animation._ANIMATIONTYPE_MATRIX = 3;
  43290. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43291. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43292. Animation._ANIMATIONTYPE_SIZE = 6;
  43293. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43294. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43295. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43296. return Animation;
  43297. }());
  43298. BABYLON.Animation = Animation;
  43299. })(BABYLON || (BABYLON = {}));
  43300. //# sourceMappingURL=babylon.animation.js.map
  43301. var BABYLON;
  43302. (function (BABYLON) {
  43303. /**
  43304. * This class defines the direct association between an animation and a target
  43305. */
  43306. var TargetedAnimation = /** @class */ (function () {
  43307. function TargetedAnimation() {
  43308. }
  43309. return TargetedAnimation;
  43310. }());
  43311. BABYLON.TargetedAnimation = TargetedAnimation;
  43312. /**
  43313. * Use this class to create coordinated animations on multiple targets
  43314. */
  43315. var AnimationGroup = /** @class */ (function () {
  43316. function AnimationGroup(name, scene) {
  43317. if (scene === void 0) { scene = null; }
  43318. this.name = name;
  43319. this._targetedAnimations = new Array();
  43320. this._animatables = new Array();
  43321. this._from = Number.MAX_VALUE;
  43322. this._to = -Number.MAX_VALUE;
  43323. this._speedRatio = 1;
  43324. this.onAnimationEndObservable = new BABYLON.Observable();
  43325. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43326. this._scene.animationGroups.push(this);
  43327. }
  43328. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43329. /**
  43330. * Define if the animations are started
  43331. */
  43332. get: function () {
  43333. return this._isStarted;
  43334. },
  43335. enumerable: true,
  43336. configurable: true
  43337. });
  43338. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43339. /**
  43340. * Gets or sets the speed ratio to use for all animations
  43341. */
  43342. get: function () {
  43343. return this._speedRatio;
  43344. },
  43345. /**
  43346. * Gets or sets the speed ratio to use for all animations
  43347. */
  43348. set: function (value) {
  43349. if (this._speedRatio === value) {
  43350. return;
  43351. }
  43352. this._speedRatio = value;
  43353. for (var index = 0; index < this._animatables.length; index++) {
  43354. var animatable = this._animatables[index];
  43355. animatable.speedRatio = this._speedRatio;
  43356. }
  43357. },
  43358. enumerable: true,
  43359. configurable: true
  43360. });
  43361. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43362. /**
  43363. * Gets the targeted animations for this animation group
  43364. */
  43365. get: function () {
  43366. return this._targetedAnimations;
  43367. },
  43368. enumerable: true,
  43369. configurable: true
  43370. });
  43371. /**
  43372. * Add an animation (with its target) in the group
  43373. * @param animation defines the animation we want to add
  43374. * @param target defines the target of the animation
  43375. * @returns the {BABYLON.TargetedAnimation} object
  43376. */
  43377. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43378. var targetedAnimation = {
  43379. animation: animation,
  43380. target: target
  43381. };
  43382. var keys = animation.getKeys();
  43383. if (this._from > keys[0].frame) {
  43384. this._from = keys[0].frame;
  43385. }
  43386. if (this._to < keys[keys.length - 1].frame) {
  43387. this._to = keys[keys.length - 1].frame;
  43388. }
  43389. this._targetedAnimations.push(targetedAnimation);
  43390. return targetedAnimation;
  43391. };
  43392. /**
  43393. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43394. * It can add constant keys at begin or end
  43395. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43396. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43397. */
  43398. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43399. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43400. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43401. beginFrame = Math.max(beginFrame, this._from);
  43402. endFrame = Math.min(endFrame, this._to);
  43403. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43404. var targetedAnimation = this._targetedAnimations[index];
  43405. var keys = targetedAnimation.animation.getKeys();
  43406. var startKey = keys[0];
  43407. var endKey = keys[keys.length - 1];
  43408. if (startKey.frame > beginFrame) {
  43409. var newKey = {
  43410. frame: beginFrame,
  43411. value: startKey.value,
  43412. inTangent: startKey.inTangent,
  43413. outTangent: startKey.outTangent,
  43414. interpolation: startKey.interpolation
  43415. };
  43416. keys.splice(0, 0, newKey);
  43417. }
  43418. if (endKey.frame < endFrame) {
  43419. var newKey = {
  43420. frame: endFrame,
  43421. value: endKey.value,
  43422. inTangent: endKey.outTangent,
  43423. outTangent: endKey.outTangent,
  43424. interpolation: endKey.interpolation
  43425. };
  43426. keys.push(newKey);
  43427. }
  43428. }
  43429. return this;
  43430. };
  43431. /**
  43432. * Start all animations on given targets
  43433. * @param loop defines if animations must loop
  43434. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43435. */
  43436. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43437. var _this = this;
  43438. if (loop === void 0) { loop = false; }
  43439. if (speedRatio === void 0) { speedRatio = 1; }
  43440. if (this._isStarted || this._targetedAnimations.length === 0) {
  43441. return this;
  43442. }
  43443. var _loop_1 = function () {
  43444. var targetedAnimation = this_1._targetedAnimations[index];
  43445. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43446. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43447. }));
  43448. };
  43449. var this_1 = this;
  43450. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43451. _loop_1();
  43452. }
  43453. this._speedRatio = speedRatio;
  43454. this._isStarted = true;
  43455. return this;
  43456. };
  43457. /**
  43458. * Pause all animations
  43459. */
  43460. AnimationGroup.prototype.pause = function () {
  43461. if (!this._isStarted) {
  43462. return this;
  43463. }
  43464. for (var index = 0; index < this._animatables.length; index++) {
  43465. var animatable = this._animatables[index];
  43466. animatable.pause();
  43467. }
  43468. return this;
  43469. };
  43470. /**
  43471. * Play all animations to initial state
  43472. * This function will start() the animations if they were not started or will restart() them if they were paused
  43473. * @param loop defines if animations must loop
  43474. */
  43475. AnimationGroup.prototype.play = function (loop) {
  43476. if (this.isStarted) {
  43477. if (loop !== undefined) {
  43478. for (var index = 0; index < this._animatables.length; index++) {
  43479. var animatable = this._animatables[index];
  43480. animatable.loopAnimation = loop;
  43481. }
  43482. }
  43483. this.restart();
  43484. }
  43485. else {
  43486. this.start(loop, this._speedRatio);
  43487. }
  43488. return this;
  43489. };
  43490. /**
  43491. * Reset all animations to initial state
  43492. */
  43493. AnimationGroup.prototype.reset = function () {
  43494. if (!this._isStarted) {
  43495. return this;
  43496. }
  43497. for (var index = 0; index < this._animatables.length; index++) {
  43498. var animatable = this._animatables[index];
  43499. animatable.reset();
  43500. }
  43501. return this;
  43502. };
  43503. /**
  43504. * Restart animations from key 0
  43505. */
  43506. AnimationGroup.prototype.restart = function () {
  43507. if (!this._isStarted) {
  43508. return this;
  43509. }
  43510. for (var index = 0; index < this._animatables.length; index++) {
  43511. var animatable = this._animatables[index];
  43512. animatable.restart();
  43513. }
  43514. return this;
  43515. };
  43516. /**
  43517. * Stop all animations
  43518. */
  43519. AnimationGroup.prototype.stop = function () {
  43520. if (!this._isStarted) {
  43521. return this;
  43522. }
  43523. for (var index = 0; index < this._animatables.length; index++) {
  43524. var animatable = this._animatables[index];
  43525. animatable.stop();
  43526. }
  43527. this._isStarted = false;
  43528. return this;
  43529. };
  43530. /**
  43531. * Dispose all associated resources
  43532. */
  43533. AnimationGroup.prototype.dispose = function () {
  43534. this._targetedAnimations = [];
  43535. this._animatables = [];
  43536. var index = this._scene.animationGroups.indexOf(this);
  43537. if (index > -1) {
  43538. this._scene.animationGroups.splice(index, 1);
  43539. }
  43540. };
  43541. return AnimationGroup;
  43542. }());
  43543. BABYLON.AnimationGroup = AnimationGroup;
  43544. })(BABYLON || (BABYLON = {}));
  43545. //# sourceMappingURL=babylon.animationGroup.js.map
  43546. var BABYLON;
  43547. (function (BABYLON) {
  43548. var RuntimeAnimation = /** @class */ (function () {
  43549. function RuntimeAnimation(target, animation) {
  43550. this._offsetsCache = {};
  43551. this._highLimitsCache = {};
  43552. this._stopped = false;
  43553. this._blendingFactor = 0;
  43554. this._ratioOffset = 0;
  43555. this._animation = animation;
  43556. this._target = target;
  43557. animation._runtimeAnimations.push(this);
  43558. }
  43559. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  43560. get: function () {
  43561. return this._animation;
  43562. },
  43563. enumerable: true,
  43564. configurable: true
  43565. });
  43566. RuntimeAnimation.prototype.reset = function () {
  43567. this._offsetsCache = {};
  43568. this._highLimitsCache = {};
  43569. this.currentFrame = 0;
  43570. this._blendingFactor = 0;
  43571. this._originalBlendValue = null;
  43572. };
  43573. RuntimeAnimation.prototype.isStopped = function () {
  43574. return this._stopped;
  43575. };
  43576. RuntimeAnimation.prototype.dispose = function () {
  43577. var index = this._animation.runtimeAnimations.indexOf(this);
  43578. if (index > -1) {
  43579. this._animation.runtimeAnimations.splice(index, 1);
  43580. }
  43581. };
  43582. RuntimeAnimation.prototype._getKeyValue = function (value) {
  43583. if (typeof value === "function") {
  43584. return value();
  43585. }
  43586. return value;
  43587. };
  43588. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  43589. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  43590. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  43591. }
  43592. this.currentFrame = currentFrame;
  43593. var keys = this._animation.getKeys();
  43594. // Try to get a hash to find the right key
  43595. 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));
  43596. if (keys[startKeyIndex].frame >= currentFrame) {
  43597. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  43598. startKeyIndex--;
  43599. }
  43600. }
  43601. for (var key = startKeyIndex; key < keys.length; key++) {
  43602. var endKey = keys[key + 1];
  43603. if (endKey.frame >= currentFrame) {
  43604. var startKey = keys[key];
  43605. var startValue = this._getKeyValue(startKey.value);
  43606. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  43607. return startValue;
  43608. }
  43609. var endValue = this._getKeyValue(endKey.value);
  43610. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  43611. var frameDelta = endKey.frame - startKey.frame;
  43612. // gradient : percent of currentFrame between the frame inf and the frame sup
  43613. var gradient = (currentFrame - startKey.frame) / frameDelta;
  43614. // check for easingFunction and correction of gradient
  43615. var easingFunction = this._animation.getEasingFunction();
  43616. if (easingFunction != null) {
  43617. gradient = easingFunction.ease(gradient);
  43618. }
  43619. switch (this._animation.dataType) {
  43620. // Float
  43621. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43622. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  43623. switch (loopMode) {
  43624. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43625. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43626. return floatValue;
  43627. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43628. return offsetValue * repeatCount + floatValue;
  43629. }
  43630. break;
  43631. // Quaternion
  43632. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43633. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  43634. switch (loopMode) {
  43635. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43636. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43637. return quatValue;
  43638. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43639. return quatValue.add(offsetValue.scale(repeatCount));
  43640. }
  43641. return quatValue;
  43642. // Vector3
  43643. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43644. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  43645. switch (loopMode) {
  43646. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43647. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43648. return vec3Value;
  43649. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43650. return vec3Value.add(offsetValue.scale(repeatCount));
  43651. }
  43652. // Vector2
  43653. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43654. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  43655. switch (loopMode) {
  43656. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43657. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43658. return vec2Value;
  43659. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43660. return vec2Value.add(offsetValue.scale(repeatCount));
  43661. }
  43662. // Size
  43663. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43664. switch (loopMode) {
  43665. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43666. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43667. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  43668. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43669. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43670. }
  43671. // Color3
  43672. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43673. switch (loopMode) {
  43674. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43675. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43676. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  43677. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43678. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43679. }
  43680. // Matrix
  43681. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  43682. switch (loopMode) {
  43683. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43684. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43685. if (BABYLON.Animation.AllowMatricesInterpolation) {
  43686. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  43687. }
  43688. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43689. return startValue;
  43690. }
  43691. default:
  43692. break;
  43693. }
  43694. break;
  43695. }
  43696. }
  43697. return this._getKeyValue(keys[keys.length - 1].value);
  43698. };
  43699. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  43700. if (blend === void 0) { blend = false; }
  43701. // Set value
  43702. var path;
  43703. var destination;
  43704. var targetPropertyPath = this._animation.targetPropertyPath;
  43705. if (targetPropertyPath.length > 1) {
  43706. var property = this._target[targetPropertyPath[0]];
  43707. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  43708. property = property[targetPropertyPath[index]];
  43709. }
  43710. path = targetPropertyPath[targetPropertyPath.length - 1];
  43711. destination = property;
  43712. }
  43713. else {
  43714. path = targetPropertyPath[0];
  43715. destination = this._target;
  43716. }
  43717. // Blending
  43718. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  43719. if (!this._originalBlendValue) {
  43720. if (destination[path].clone) {
  43721. this._originalBlendValue = destination[path].clone();
  43722. }
  43723. else {
  43724. this._originalBlendValue = destination[path];
  43725. }
  43726. }
  43727. if (this._originalBlendValue.prototype) {
  43728. if (this._originalBlendValue.prototype.Lerp) {
  43729. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  43730. }
  43731. else {
  43732. destination[path] = currentValue;
  43733. }
  43734. }
  43735. else if (this._originalBlendValue.m) {
  43736. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  43737. }
  43738. else {
  43739. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  43740. }
  43741. this._blendingFactor += this._animation.blendingSpeed;
  43742. }
  43743. else {
  43744. destination[path] = currentValue;
  43745. }
  43746. if (this._target.markAsDirty) {
  43747. this._target.markAsDirty(this._animation.targetProperty);
  43748. }
  43749. };
  43750. RuntimeAnimation.prototype.goToFrame = function (frame) {
  43751. var keys = this._animation.getKeys();
  43752. if (frame < keys[0].frame) {
  43753. frame = keys[0].frame;
  43754. }
  43755. else if (frame > keys[keys.length - 1].frame) {
  43756. frame = keys[keys.length - 1].frame;
  43757. }
  43758. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  43759. this.setValue(currentValue);
  43760. };
  43761. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  43762. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  43763. this._ratioOffset = this._previousRatio - newRatio;
  43764. };
  43765. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  43766. if (blend === void 0) { blend = false; }
  43767. var targetPropertyPath = this._animation.targetPropertyPath;
  43768. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  43769. this._stopped = true;
  43770. return false;
  43771. }
  43772. var returnValue = true;
  43773. var keys = this._animation.getKeys();
  43774. // Adding a start key at frame 0 if missing
  43775. if (keys[0].frame !== 0) {
  43776. var newKey = { frame: 0, value: keys[0].value };
  43777. keys.splice(0, 0, newKey);
  43778. }
  43779. // Check limits
  43780. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  43781. from = keys[0].frame;
  43782. }
  43783. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  43784. to = keys[keys.length - 1].frame;
  43785. }
  43786. //to and from cannot be the same key
  43787. if (from === to) {
  43788. if (from > keys[0].frame) {
  43789. from--;
  43790. }
  43791. else if (to < keys[keys.length - 1].frame) {
  43792. to++;
  43793. }
  43794. }
  43795. // Compute ratio
  43796. var range = to - from;
  43797. var offsetValue;
  43798. // ratio represents the frame delta between from and to
  43799. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  43800. var highLimitValue = 0;
  43801. this._previousDelay = delay;
  43802. this._previousRatio = ratio;
  43803. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  43804. returnValue = false;
  43805. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  43806. }
  43807. else {
  43808. // Get max value if required
  43809. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  43810. var keyOffset = to.toString() + from.toString();
  43811. if (!this._offsetsCache[keyOffset]) {
  43812. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43813. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  43814. switch (this._animation.dataType) {
  43815. // Float
  43816. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43817. this._offsetsCache[keyOffset] = toValue - fromValue;
  43818. break;
  43819. // Quaternion
  43820. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43821. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43822. break;
  43823. // Vector3
  43824. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43825. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43826. // Vector2
  43827. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43828. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43829. // Size
  43830. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43831. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43832. // Color3
  43833. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43834. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  43835. default:
  43836. break;
  43837. }
  43838. this._highLimitsCache[keyOffset] = toValue;
  43839. }
  43840. highLimitValue = this._highLimitsCache[keyOffset];
  43841. offsetValue = this._offsetsCache[keyOffset];
  43842. }
  43843. }
  43844. if (offsetValue === undefined) {
  43845. switch (this._animation.dataType) {
  43846. // Float
  43847. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43848. offsetValue = 0;
  43849. break;
  43850. // Quaternion
  43851. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43852. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  43853. break;
  43854. // Vector3
  43855. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43856. offsetValue = BABYLON.Vector3.Zero();
  43857. break;
  43858. // Vector2
  43859. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43860. offsetValue = BABYLON.Vector2.Zero();
  43861. break;
  43862. // Size
  43863. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43864. offsetValue = BABYLON.Size.Zero();
  43865. break;
  43866. // Color3
  43867. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43868. offsetValue = BABYLON.Color3.Black();
  43869. }
  43870. }
  43871. // Compute value
  43872. var repeatCount = (ratio / range) >> 0;
  43873. var currentFrame = returnValue ? from + ratio % range : to;
  43874. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  43875. // Set value
  43876. this.setValue(currentValue);
  43877. // Check events
  43878. var events = this._animation.getEvents();
  43879. for (var index = 0; index < events.length; index++) {
  43880. // Make sure current frame has passed event frame and that event frame is within the current range
  43881. // Also, handle both forward and reverse animations
  43882. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  43883. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  43884. var event = events[index];
  43885. if (!event.isDone) {
  43886. // If event should be done only once, remove it.
  43887. if (event.onlyOnce) {
  43888. events.splice(index, 1);
  43889. index--;
  43890. }
  43891. event.isDone = true;
  43892. event.action();
  43893. } // Don't do anything if the event has already be done.
  43894. }
  43895. else if (events[index].isDone && !events[index].onlyOnce) {
  43896. // reset event, the animation is looping
  43897. events[index].isDone = false;
  43898. }
  43899. }
  43900. if (!returnValue) {
  43901. this._stopped = true;
  43902. }
  43903. return returnValue;
  43904. };
  43905. return RuntimeAnimation;
  43906. }());
  43907. BABYLON.RuntimeAnimation = RuntimeAnimation;
  43908. })(BABYLON || (BABYLON = {}));
  43909. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  43910. var BABYLON;
  43911. (function (BABYLON) {
  43912. var Animatable = /** @class */ (function () {
  43913. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  43914. if (fromFrame === void 0) { fromFrame = 0; }
  43915. if (toFrame === void 0) { toFrame = 100; }
  43916. if (loopAnimation === void 0) { loopAnimation = false; }
  43917. if (speedRatio === void 0) { speedRatio = 1.0; }
  43918. this.target = target;
  43919. this.fromFrame = fromFrame;
  43920. this.toFrame = toFrame;
  43921. this.loopAnimation = loopAnimation;
  43922. this.onAnimationEnd = onAnimationEnd;
  43923. this._localDelayOffset = null;
  43924. this._pausedDelay = null;
  43925. this._runtimeAnimations = new Array();
  43926. this._paused = false;
  43927. this._speedRatio = 1;
  43928. this.animationStarted = false;
  43929. if (animations) {
  43930. this.appendAnimations(target, animations);
  43931. }
  43932. this._speedRatio = speedRatio;
  43933. this._scene = scene;
  43934. scene._activeAnimatables.push(this);
  43935. }
  43936. Object.defineProperty(Animatable.prototype, "speedRatio", {
  43937. get: function () {
  43938. return this._speedRatio;
  43939. },
  43940. set: function (value) {
  43941. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  43942. var animation = this._runtimeAnimations[index];
  43943. animation._prepareForSpeedRatioChange(value);
  43944. }
  43945. this._speedRatio = value;
  43946. },
  43947. enumerable: true,
  43948. configurable: true
  43949. });
  43950. // Methods
  43951. Animatable.prototype.getAnimations = function () {
  43952. return this._runtimeAnimations;
  43953. };
  43954. Animatable.prototype.appendAnimations = function (target, animations) {
  43955. for (var index = 0; index < animations.length; index++) {
  43956. var animation = animations[index];
  43957. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43958. }
  43959. };
  43960. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43961. var runtimeAnimations = this._runtimeAnimations;
  43962. for (var index = 0; index < runtimeAnimations.length; index++) {
  43963. if (runtimeAnimations[index].animation.targetProperty === property) {
  43964. return runtimeAnimations[index].animation;
  43965. }
  43966. }
  43967. return null;
  43968. };
  43969. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43970. var runtimeAnimations = this._runtimeAnimations;
  43971. for (var index = 0; index < runtimeAnimations.length; index++) {
  43972. if (runtimeAnimations[index].animation.targetProperty === property) {
  43973. return runtimeAnimations[index];
  43974. }
  43975. }
  43976. return null;
  43977. };
  43978. Animatable.prototype.reset = function () {
  43979. var runtimeAnimations = this._runtimeAnimations;
  43980. for (var index = 0; index < runtimeAnimations.length; index++) {
  43981. runtimeAnimations[index].reset();
  43982. }
  43983. // Reset to original value
  43984. for (index = 0; index < runtimeAnimations.length; index++) {
  43985. var animation = runtimeAnimations[index];
  43986. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43987. }
  43988. this._localDelayOffset = null;
  43989. this._pausedDelay = null;
  43990. };
  43991. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43992. var runtimeAnimations = this._runtimeAnimations;
  43993. for (var index = 0; index < runtimeAnimations.length; index++) {
  43994. runtimeAnimations[index].animation.enableBlending = true;
  43995. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43996. }
  43997. };
  43998. Animatable.prototype.disableBlending = function () {
  43999. var runtimeAnimations = this._runtimeAnimations;
  44000. for (var index = 0; index < runtimeAnimations.length; index++) {
  44001. runtimeAnimations[index].animation.enableBlending = false;
  44002. }
  44003. };
  44004. Animatable.prototype.goToFrame = function (frame) {
  44005. var runtimeAnimations = this._runtimeAnimations;
  44006. if (runtimeAnimations[0]) {
  44007. var fps = runtimeAnimations[0].animation.framePerSecond;
  44008. var currentFrame = runtimeAnimations[0].currentFrame;
  44009. var adjustTime = frame - currentFrame;
  44010. var delay = adjustTime * 1000 / fps;
  44011. if (this._localDelayOffset === null) {
  44012. this._localDelayOffset = 0;
  44013. }
  44014. this._localDelayOffset -= delay;
  44015. }
  44016. for (var index = 0; index < runtimeAnimations.length; index++) {
  44017. runtimeAnimations[index].goToFrame(frame);
  44018. }
  44019. };
  44020. Animatable.prototype.pause = function () {
  44021. if (this._paused) {
  44022. return;
  44023. }
  44024. this._paused = true;
  44025. };
  44026. Animatable.prototype.restart = function () {
  44027. this._paused = false;
  44028. };
  44029. Animatable.prototype.stop = function (animationName) {
  44030. if (animationName) {
  44031. var idx = this._scene._activeAnimatables.indexOf(this);
  44032. if (idx > -1) {
  44033. var runtimeAnimations = this._runtimeAnimations;
  44034. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  44035. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  44036. continue;
  44037. }
  44038. runtimeAnimations[index].dispose();
  44039. runtimeAnimations.splice(index, 1);
  44040. }
  44041. if (runtimeAnimations.length == 0) {
  44042. this._scene._activeAnimatables.splice(idx, 1);
  44043. if (this.onAnimationEnd) {
  44044. this.onAnimationEnd();
  44045. }
  44046. }
  44047. }
  44048. }
  44049. else {
  44050. var index = this._scene._activeAnimatables.indexOf(this);
  44051. if (index > -1) {
  44052. this._scene._activeAnimatables.splice(index, 1);
  44053. var runtimeAnimations = this._runtimeAnimations;
  44054. for (var index = 0; index < runtimeAnimations.length; index++) {
  44055. runtimeAnimations[index].dispose();
  44056. }
  44057. if (this.onAnimationEnd) {
  44058. this.onAnimationEnd();
  44059. }
  44060. }
  44061. }
  44062. };
  44063. Animatable.prototype._animate = function (delay) {
  44064. if (this._paused) {
  44065. this.animationStarted = false;
  44066. if (this._pausedDelay === null) {
  44067. this._pausedDelay = delay;
  44068. }
  44069. return true;
  44070. }
  44071. if (this._localDelayOffset === null) {
  44072. this._localDelayOffset = delay;
  44073. }
  44074. else if (this._pausedDelay !== null) {
  44075. this._localDelayOffset += delay - this._pausedDelay;
  44076. this._pausedDelay = null;
  44077. }
  44078. // Animating
  44079. var running = false;
  44080. var runtimeAnimations = this._runtimeAnimations;
  44081. var index;
  44082. for (index = 0; index < runtimeAnimations.length; index++) {
  44083. var animation = runtimeAnimations[index];
  44084. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  44085. running = running || isRunning;
  44086. }
  44087. this.animationStarted = running;
  44088. if (!running) {
  44089. // Remove from active animatables
  44090. index = this._scene._activeAnimatables.indexOf(this);
  44091. this._scene._activeAnimatables.splice(index, 1);
  44092. // Dispose all runtime animations
  44093. for (index = 0; index < runtimeAnimations.length; index++) {
  44094. runtimeAnimations[index].dispose();
  44095. }
  44096. }
  44097. if (!running && this.onAnimationEnd) {
  44098. this.onAnimationEnd();
  44099. this.onAnimationEnd = null;
  44100. }
  44101. return running;
  44102. };
  44103. return Animatable;
  44104. }());
  44105. BABYLON.Animatable = Animatable;
  44106. })(BABYLON || (BABYLON = {}));
  44107. //# sourceMappingURL=babylon.animatable.js.map
  44108. var BABYLON;
  44109. (function (BABYLON) {
  44110. var EasingFunction = /** @class */ (function () {
  44111. function EasingFunction() {
  44112. // Properties
  44113. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  44114. }
  44115. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  44116. get: function () {
  44117. return EasingFunction._EASINGMODE_EASEIN;
  44118. },
  44119. enumerable: true,
  44120. configurable: true
  44121. });
  44122. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  44123. get: function () {
  44124. return EasingFunction._EASINGMODE_EASEOUT;
  44125. },
  44126. enumerable: true,
  44127. configurable: true
  44128. });
  44129. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  44130. get: function () {
  44131. return EasingFunction._EASINGMODE_EASEINOUT;
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. EasingFunction.prototype.setEasingMode = function (easingMode) {
  44137. var n = Math.min(Math.max(easingMode, 0), 2);
  44138. this._easingMode = n;
  44139. };
  44140. EasingFunction.prototype.getEasingMode = function () {
  44141. return this._easingMode;
  44142. };
  44143. EasingFunction.prototype.easeInCore = function (gradient) {
  44144. throw new Error('You must implement this method');
  44145. };
  44146. EasingFunction.prototype.ease = function (gradient) {
  44147. switch (this._easingMode) {
  44148. case EasingFunction.EASINGMODE_EASEIN:
  44149. return this.easeInCore(gradient);
  44150. case EasingFunction.EASINGMODE_EASEOUT:
  44151. return (1 - this.easeInCore(1 - gradient));
  44152. }
  44153. if (gradient >= 0.5) {
  44154. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  44155. }
  44156. return (this.easeInCore(gradient * 2) * 0.5);
  44157. };
  44158. //Statics
  44159. EasingFunction._EASINGMODE_EASEIN = 0;
  44160. EasingFunction._EASINGMODE_EASEOUT = 1;
  44161. EasingFunction._EASINGMODE_EASEINOUT = 2;
  44162. return EasingFunction;
  44163. }());
  44164. BABYLON.EasingFunction = EasingFunction;
  44165. var CircleEase = /** @class */ (function (_super) {
  44166. __extends(CircleEase, _super);
  44167. function CircleEase() {
  44168. return _super !== null && _super.apply(this, arguments) || this;
  44169. }
  44170. CircleEase.prototype.easeInCore = function (gradient) {
  44171. gradient = Math.max(0, Math.min(1, gradient));
  44172. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  44173. };
  44174. return CircleEase;
  44175. }(EasingFunction));
  44176. BABYLON.CircleEase = CircleEase;
  44177. var BackEase = /** @class */ (function (_super) {
  44178. __extends(BackEase, _super);
  44179. function BackEase(amplitude) {
  44180. if (amplitude === void 0) { amplitude = 1; }
  44181. var _this = _super.call(this) || this;
  44182. _this.amplitude = amplitude;
  44183. return _this;
  44184. }
  44185. BackEase.prototype.easeInCore = function (gradient) {
  44186. var num = Math.max(0, this.amplitude);
  44187. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  44188. };
  44189. return BackEase;
  44190. }(EasingFunction));
  44191. BABYLON.BackEase = BackEase;
  44192. var BounceEase = /** @class */ (function (_super) {
  44193. __extends(BounceEase, _super);
  44194. function BounceEase(bounces, bounciness) {
  44195. if (bounces === void 0) { bounces = 3; }
  44196. if (bounciness === void 0) { bounciness = 2; }
  44197. var _this = _super.call(this) || this;
  44198. _this.bounces = bounces;
  44199. _this.bounciness = bounciness;
  44200. return _this;
  44201. }
  44202. BounceEase.prototype.easeInCore = function (gradient) {
  44203. var y = Math.max(0.0, this.bounces);
  44204. var bounciness = this.bounciness;
  44205. if (bounciness <= 1.0) {
  44206. bounciness = 1.001;
  44207. }
  44208. var num9 = Math.pow(bounciness, y);
  44209. var num5 = 1.0 - bounciness;
  44210. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44211. var num15 = gradient * num4;
  44212. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44213. var num3 = Math.floor(num65);
  44214. var num13 = num3 + 1.0;
  44215. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44216. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44217. var num7 = (num8 + num12) * 0.5;
  44218. var num6 = gradient - num7;
  44219. var num2 = num7 - num8;
  44220. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44221. };
  44222. return BounceEase;
  44223. }(EasingFunction));
  44224. BABYLON.BounceEase = BounceEase;
  44225. var CubicEase = /** @class */ (function (_super) {
  44226. __extends(CubicEase, _super);
  44227. function CubicEase() {
  44228. return _super !== null && _super.apply(this, arguments) || this;
  44229. }
  44230. CubicEase.prototype.easeInCore = function (gradient) {
  44231. return (gradient * gradient * gradient);
  44232. };
  44233. return CubicEase;
  44234. }(EasingFunction));
  44235. BABYLON.CubicEase = CubicEase;
  44236. var ElasticEase = /** @class */ (function (_super) {
  44237. __extends(ElasticEase, _super);
  44238. function ElasticEase(oscillations, springiness) {
  44239. if (oscillations === void 0) { oscillations = 3; }
  44240. if (springiness === void 0) { springiness = 3; }
  44241. var _this = _super.call(this) || this;
  44242. _this.oscillations = oscillations;
  44243. _this.springiness = springiness;
  44244. return _this;
  44245. }
  44246. ElasticEase.prototype.easeInCore = function (gradient) {
  44247. var num2;
  44248. var num3 = Math.max(0.0, this.oscillations);
  44249. var num = Math.max(0.0, this.springiness);
  44250. if (num == 0) {
  44251. num2 = gradient;
  44252. }
  44253. else {
  44254. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44255. }
  44256. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44257. };
  44258. return ElasticEase;
  44259. }(EasingFunction));
  44260. BABYLON.ElasticEase = ElasticEase;
  44261. var ExponentialEase = /** @class */ (function (_super) {
  44262. __extends(ExponentialEase, _super);
  44263. function ExponentialEase(exponent) {
  44264. if (exponent === void 0) { exponent = 2; }
  44265. var _this = _super.call(this) || this;
  44266. _this.exponent = exponent;
  44267. return _this;
  44268. }
  44269. ExponentialEase.prototype.easeInCore = function (gradient) {
  44270. if (this.exponent <= 0) {
  44271. return gradient;
  44272. }
  44273. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44274. };
  44275. return ExponentialEase;
  44276. }(EasingFunction));
  44277. BABYLON.ExponentialEase = ExponentialEase;
  44278. var PowerEase = /** @class */ (function (_super) {
  44279. __extends(PowerEase, _super);
  44280. function PowerEase(power) {
  44281. if (power === void 0) { power = 2; }
  44282. var _this = _super.call(this) || this;
  44283. _this.power = power;
  44284. return _this;
  44285. }
  44286. PowerEase.prototype.easeInCore = function (gradient) {
  44287. var y = Math.max(0.0, this.power);
  44288. return Math.pow(gradient, y);
  44289. };
  44290. return PowerEase;
  44291. }(EasingFunction));
  44292. BABYLON.PowerEase = PowerEase;
  44293. var QuadraticEase = /** @class */ (function (_super) {
  44294. __extends(QuadraticEase, _super);
  44295. function QuadraticEase() {
  44296. return _super !== null && _super.apply(this, arguments) || this;
  44297. }
  44298. QuadraticEase.prototype.easeInCore = function (gradient) {
  44299. return (gradient * gradient);
  44300. };
  44301. return QuadraticEase;
  44302. }(EasingFunction));
  44303. BABYLON.QuadraticEase = QuadraticEase;
  44304. var QuarticEase = /** @class */ (function (_super) {
  44305. __extends(QuarticEase, _super);
  44306. function QuarticEase() {
  44307. return _super !== null && _super.apply(this, arguments) || this;
  44308. }
  44309. QuarticEase.prototype.easeInCore = function (gradient) {
  44310. return (gradient * gradient * gradient * gradient);
  44311. };
  44312. return QuarticEase;
  44313. }(EasingFunction));
  44314. BABYLON.QuarticEase = QuarticEase;
  44315. var QuinticEase = /** @class */ (function (_super) {
  44316. __extends(QuinticEase, _super);
  44317. function QuinticEase() {
  44318. return _super !== null && _super.apply(this, arguments) || this;
  44319. }
  44320. QuinticEase.prototype.easeInCore = function (gradient) {
  44321. return (gradient * gradient * gradient * gradient * gradient);
  44322. };
  44323. return QuinticEase;
  44324. }(EasingFunction));
  44325. BABYLON.QuinticEase = QuinticEase;
  44326. var SineEase = /** @class */ (function (_super) {
  44327. __extends(SineEase, _super);
  44328. function SineEase() {
  44329. return _super !== null && _super.apply(this, arguments) || this;
  44330. }
  44331. SineEase.prototype.easeInCore = function (gradient) {
  44332. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44333. };
  44334. return SineEase;
  44335. }(EasingFunction));
  44336. BABYLON.SineEase = SineEase;
  44337. var BezierCurveEase = /** @class */ (function (_super) {
  44338. __extends(BezierCurveEase, _super);
  44339. function BezierCurveEase(x1, y1, x2, y2) {
  44340. if (x1 === void 0) { x1 = 0; }
  44341. if (y1 === void 0) { y1 = 0; }
  44342. if (x2 === void 0) { x2 = 1; }
  44343. if (y2 === void 0) { y2 = 1; }
  44344. var _this = _super.call(this) || this;
  44345. _this.x1 = x1;
  44346. _this.y1 = y1;
  44347. _this.x2 = x2;
  44348. _this.y2 = y2;
  44349. return _this;
  44350. }
  44351. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44352. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44353. };
  44354. return BezierCurveEase;
  44355. }(EasingFunction));
  44356. BABYLON.BezierCurveEase = BezierCurveEase;
  44357. })(BABYLON || (BABYLON = {}));
  44358. //# sourceMappingURL=babylon.easing.js.map
  44359. var BABYLON;
  44360. (function (BABYLON) {
  44361. var Condition = /** @class */ (function () {
  44362. function Condition(actionManager) {
  44363. this._actionManager = actionManager;
  44364. }
  44365. Condition.prototype.isValid = function () {
  44366. return true;
  44367. };
  44368. Condition.prototype._getProperty = function (propertyPath) {
  44369. return this._actionManager._getProperty(propertyPath);
  44370. };
  44371. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44372. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44373. };
  44374. Condition.prototype.serialize = function () {
  44375. };
  44376. Condition.prototype._serialize = function (serializedCondition) {
  44377. return {
  44378. type: 2,
  44379. children: [],
  44380. name: serializedCondition.name,
  44381. properties: serializedCondition.properties
  44382. };
  44383. };
  44384. return Condition;
  44385. }());
  44386. BABYLON.Condition = Condition;
  44387. var ValueCondition = /** @class */ (function (_super) {
  44388. __extends(ValueCondition, _super);
  44389. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44390. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44391. var _this = _super.call(this, actionManager) || this;
  44392. _this.propertyPath = propertyPath;
  44393. _this.value = value;
  44394. _this.operator = operator;
  44395. _this._target = target;
  44396. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44397. _this._property = _this._getProperty(_this.propertyPath);
  44398. return _this;
  44399. }
  44400. Object.defineProperty(ValueCondition, "IsEqual", {
  44401. get: function () {
  44402. return ValueCondition._IsEqual;
  44403. },
  44404. enumerable: true,
  44405. configurable: true
  44406. });
  44407. Object.defineProperty(ValueCondition, "IsDifferent", {
  44408. get: function () {
  44409. return ValueCondition._IsDifferent;
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. Object.defineProperty(ValueCondition, "IsGreater", {
  44415. get: function () {
  44416. return ValueCondition._IsGreater;
  44417. },
  44418. enumerable: true,
  44419. configurable: true
  44420. });
  44421. Object.defineProperty(ValueCondition, "IsLesser", {
  44422. get: function () {
  44423. return ValueCondition._IsLesser;
  44424. },
  44425. enumerable: true,
  44426. configurable: true
  44427. });
  44428. // Methods
  44429. ValueCondition.prototype.isValid = function () {
  44430. switch (this.operator) {
  44431. case ValueCondition.IsGreater:
  44432. return this._effectiveTarget[this._property] > this.value;
  44433. case ValueCondition.IsLesser:
  44434. return this._effectiveTarget[this._property] < this.value;
  44435. case ValueCondition.IsEqual:
  44436. case ValueCondition.IsDifferent:
  44437. var check;
  44438. if (this.value.equals) {
  44439. check = this.value.equals(this._effectiveTarget[this._property]);
  44440. }
  44441. else {
  44442. check = this.value === this._effectiveTarget[this._property];
  44443. }
  44444. return this.operator === ValueCondition.IsEqual ? check : !check;
  44445. }
  44446. return false;
  44447. };
  44448. ValueCondition.prototype.serialize = function () {
  44449. return this._serialize({
  44450. name: "ValueCondition",
  44451. properties: [
  44452. BABYLON.Action._GetTargetProperty(this._target),
  44453. { name: "propertyPath", value: this.propertyPath },
  44454. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44455. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44456. ]
  44457. });
  44458. };
  44459. ValueCondition.GetOperatorName = function (operator) {
  44460. switch (operator) {
  44461. case ValueCondition._IsEqual: return "IsEqual";
  44462. case ValueCondition._IsDifferent: return "IsDifferent";
  44463. case ValueCondition._IsGreater: return "IsGreater";
  44464. case ValueCondition._IsLesser: return "IsLesser";
  44465. default: return "";
  44466. }
  44467. };
  44468. // Statics
  44469. ValueCondition._IsEqual = 0;
  44470. ValueCondition._IsDifferent = 1;
  44471. ValueCondition._IsGreater = 2;
  44472. ValueCondition._IsLesser = 3;
  44473. return ValueCondition;
  44474. }(Condition));
  44475. BABYLON.ValueCondition = ValueCondition;
  44476. var PredicateCondition = /** @class */ (function (_super) {
  44477. __extends(PredicateCondition, _super);
  44478. function PredicateCondition(actionManager, predicate) {
  44479. var _this = _super.call(this, actionManager) || this;
  44480. _this.predicate = predicate;
  44481. return _this;
  44482. }
  44483. PredicateCondition.prototype.isValid = function () {
  44484. return this.predicate();
  44485. };
  44486. return PredicateCondition;
  44487. }(Condition));
  44488. BABYLON.PredicateCondition = PredicateCondition;
  44489. var StateCondition = /** @class */ (function (_super) {
  44490. __extends(StateCondition, _super);
  44491. function StateCondition(actionManager, target, value) {
  44492. var _this = _super.call(this, actionManager) || this;
  44493. _this.value = value;
  44494. _this._target = target;
  44495. return _this;
  44496. }
  44497. // Methods
  44498. StateCondition.prototype.isValid = function () {
  44499. return this._target.state === this.value;
  44500. };
  44501. StateCondition.prototype.serialize = function () {
  44502. return this._serialize({
  44503. name: "StateCondition",
  44504. properties: [
  44505. BABYLON.Action._GetTargetProperty(this._target),
  44506. { name: "value", value: this.value }
  44507. ]
  44508. });
  44509. };
  44510. return StateCondition;
  44511. }(Condition));
  44512. BABYLON.StateCondition = StateCondition;
  44513. })(BABYLON || (BABYLON = {}));
  44514. //# sourceMappingURL=babylon.condition.js.map
  44515. var BABYLON;
  44516. (function (BABYLON) {
  44517. var Action = /** @class */ (function () {
  44518. function Action(triggerOptions, condition) {
  44519. this.triggerOptions = triggerOptions;
  44520. this.onBeforeExecuteObservable = new BABYLON.Observable();
  44521. if (triggerOptions.parameter) {
  44522. this.trigger = triggerOptions.trigger;
  44523. this._triggerParameter = triggerOptions.parameter;
  44524. }
  44525. else {
  44526. this.trigger = triggerOptions;
  44527. }
  44528. this._nextActiveAction = this;
  44529. this._condition = condition;
  44530. }
  44531. // Methods
  44532. Action.prototype._prepare = function () {
  44533. };
  44534. Action.prototype.getTriggerParameter = function () {
  44535. return this._triggerParameter;
  44536. };
  44537. Action.prototype._executeCurrent = function (evt) {
  44538. if (this._nextActiveAction._condition) {
  44539. var condition = this._nextActiveAction._condition;
  44540. var currentRenderId = this._actionManager.getScene().getRenderId();
  44541. // We cache the current evaluation for the current frame
  44542. if (condition._evaluationId === currentRenderId) {
  44543. if (!condition._currentResult) {
  44544. return;
  44545. }
  44546. }
  44547. else {
  44548. condition._evaluationId = currentRenderId;
  44549. if (!condition.isValid()) {
  44550. condition._currentResult = false;
  44551. return;
  44552. }
  44553. condition._currentResult = true;
  44554. }
  44555. }
  44556. this.onBeforeExecuteObservable.notifyObservers(this);
  44557. this._nextActiveAction.execute(evt);
  44558. this.skipToNextActiveAction();
  44559. };
  44560. Action.prototype.execute = function (evt) {
  44561. };
  44562. Action.prototype.skipToNextActiveAction = function () {
  44563. if (this._nextActiveAction._child) {
  44564. if (!this._nextActiveAction._child._actionManager) {
  44565. this._nextActiveAction._child._actionManager = this._actionManager;
  44566. }
  44567. this._nextActiveAction = this._nextActiveAction._child;
  44568. }
  44569. else {
  44570. this._nextActiveAction = this;
  44571. }
  44572. };
  44573. Action.prototype.then = function (action) {
  44574. this._child = action;
  44575. action._actionManager = this._actionManager;
  44576. action._prepare();
  44577. return action;
  44578. };
  44579. Action.prototype._getProperty = function (propertyPath) {
  44580. return this._actionManager._getProperty(propertyPath);
  44581. };
  44582. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  44583. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44584. };
  44585. Action.prototype.serialize = function (parent) {
  44586. };
  44587. // Called by BABYLON.Action objects in serialize(...). Internal use
  44588. Action.prototype._serialize = function (serializedAction, parent) {
  44589. var serializationObject = {
  44590. type: 1,
  44591. children: [],
  44592. name: serializedAction.name,
  44593. properties: serializedAction.properties || []
  44594. };
  44595. // Serialize child
  44596. if (this._child) {
  44597. this._child.serialize(serializationObject);
  44598. }
  44599. // Check if "this" has a condition
  44600. if (this._condition) {
  44601. var serializedCondition = this._condition.serialize();
  44602. serializedCondition.children.push(serializationObject);
  44603. if (parent) {
  44604. parent.children.push(serializedCondition);
  44605. }
  44606. return serializedCondition;
  44607. }
  44608. if (parent) {
  44609. parent.children.push(serializationObject);
  44610. }
  44611. return serializationObject;
  44612. };
  44613. Action._SerializeValueAsString = function (value) {
  44614. if (typeof value === "number") {
  44615. return value.toString();
  44616. }
  44617. if (typeof value === "boolean") {
  44618. return value ? "true" : "false";
  44619. }
  44620. if (value instanceof BABYLON.Vector2) {
  44621. return value.x + ", " + value.y;
  44622. }
  44623. if (value instanceof BABYLON.Vector3) {
  44624. return value.x + ", " + value.y + ", " + value.z;
  44625. }
  44626. if (value instanceof BABYLON.Color3) {
  44627. return value.r + ", " + value.g + ", " + value.b;
  44628. }
  44629. if (value instanceof BABYLON.Color4) {
  44630. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  44631. }
  44632. return value; // string
  44633. };
  44634. Action._GetTargetProperty = function (target) {
  44635. return {
  44636. name: "target",
  44637. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  44638. : target instanceof BABYLON.Light ? "LightProperties"
  44639. : target instanceof BABYLON.Camera ? "CameraProperties"
  44640. : "SceneProperties",
  44641. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  44642. };
  44643. };
  44644. return Action;
  44645. }());
  44646. BABYLON.Action = Action;
  44647. })(BABYLON || (BABYLON = {}));
  44648. //# sourceMappingURL=babylon.action.js.map
  44649. var BABYLON;
  44650. (function (BABYLON) {
  44651. /**
  44652. * ActionEvent is the event beint sent when an action is triggered.
  44653. */
  44654. var ActionEvent = /** @class */ (function () {
  44655. /**
  44656. * @param source The mesh or sprite that triggered the action.
  44657. * @param pointerX The X mouse cursor position at the time of the event
  44658. * @param pointerY The Y mouse cursor position at the time of the event
  44659. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  44660. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  44661. */
  44662. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  44663. this.source = source;
  44664. this.pointerX = pointerX;
  44665. this.pointerY = pointerY;
  44666. this.meshUnderPointer = meshUnderPointer;
  44667. this.sourceEvent = sourceEvent;
  44668. this.additionalData = additionalData;
  44669. }
  44670. /**
  44671. * Helper function to auto-create an ActionEvent from a source mesh.
  44672. * @param source The source mesh that triggered the event
  44673. * @param evt {Event} The original (browser) event
  44674. */
  44675. ActionEvent.CreateNew = function (source, evt, additionalData) {
  44676. var scene = source.getScene();
  44677. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44678. };
  44679. /**
  44680. * Helper function to auto-create an ActionEvent from a source mesh.
  44681. * @param source The source sprite that triggered the event
  44682. * @param scene Scene associated with the sprite
  44683. * @param evt {Event} The original (browser) event
  44684. */
  44685. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  44686. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44687. };
  44688. /**
  44689. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  44690. * @param scene the scene where the event occurred
  44691. * @param evt {Event} The original (browser) event
  44692. */
  44693. ActionEvent.CreateNewFromScene = function (scene, evt) {
  44694. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  44695. };
  44696. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  44697. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  44698. };
  44699. return ActionEvent;
  44700. }());
  44701. BABYLON.ActionEvent = ActionEvent;
  44702. /**
  44703. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  44704. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  44705. */
  44706. var ActionManager = /** @class */ (function () {
  44707. function ActionManager(scene) {
  44708. // Members
  44709. this.actions = new Array();
  44710. this.hoverCursor = '';
  44711. this._scene = scene;
  44712. scene._actionManagers.push(this);
  44713. }
  44714. Object.defineProperty(ActionManager, "NothingTrigger", {
  44715. get: function () {
  44716. return ActionManager._NothingTrigger;
  44717. },
  44718. enumerable: true,
  44719. configurable: true
  44720. });
  44721. Object.defineProperty(ActionManager, "OnPickTrigger", {
  44722. get: function () {
  44723. return ActionManager._OnPickTrigger;
  44724. },
  44725. enumerable: true,
  44726. configurable: true
  44727. });
  44728. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  44729. get: function () {
  44730. return ActionManager._OnLeftPickTrigger;
  44731. },
  44732. enumerable: true,
  44733. configurable: true
  44734. });
  44735. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  44736. get: function () {
  44737. return ActionManager._OnRightPickTrigger;
  44738. },
  44739. enumerable: true,
  44740. configurable: true
  44741. });
  44742. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  44743. get: function () {
  44744. return ActionManager._OnCenterPickTrigger;
  44745. },
  44746. enumerable: true,
  44747. configurable: true
  44748. });
  44749. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  44750. get: function () {
  44751. return ActionManager._OnPickDownTrigger;
  44752. },
  44753. enumerable: true,
  44754. configurable: true
  44755. });
  44756. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  44757. get: function () {
  44758. return ActionManager._OnDoublePickTrigger;
  44759. },
  44760. enumerable: true,
  44761. configurable: true
  44762. });
  44763. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  44764. get: function () {
  44765. return ActionManager._OnPickUpTrigger;
  44766. },
  44767. enumerable: true,
  44768. configurable: true
  44769. });
  44770. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  44771. /// This trigger will only be raised if you also declared a OnPickDown
  44772. get: function () {
  44773. return ActionManager._OnPickOutTrigger;
  44774. },
  44775. enumerable: true,
  44776. configurable: true
  44777. });
  44778. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  44779. get: function () {
  44780. return ActionManager._OnLongPressTrigger;
  44781. },
  44782. enumerable: true,
  44783. configurable: true
  44784. });
  44785. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  44786. get: function () {
  44787. return ActionManager._OnPointerOverTrigger;
  44788. },
  44789. enumerable: true,
  44790. configurable: true
  44791. });
  44792. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  44793. get: function () {
  44794. return ActionManager._OnPointerOutTrigger;
  44795. },
  44796. enumerable: true,
  44797. configurable: true
  44798. });
  44799. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  44800. get: function () {
  44801. return ActionManager._OnEveryFrameTrigger;
  44802. },
  44803. enumerable: true,
  44804. configurable: true
  44805. });
  44806. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  44807. get: function () {
  44808. return ActionManager._OnIntersectionEnterTrigger;
  44809. },
  44810. enumerable: true,
  44811. configurable: true
  44812. });
  44813. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  44814. get: function () {
  44815. return ActionManager._OnIntersectionExitTrigger;
  44816. },
  44817. enumerable: true,
  44818. configurable: true
  44819. });
  44820. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  44821. get: function () {
  44822. return ActionManager._OnKeyDownTrigger;
  44823. },
  44824. enumerable: true,
  44825. configurable: true
  44826. });
  44827. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  44828. get: function () {
  44829. return ActionManager._OnKeyUpTrigger;
  44830. },
  44831. enumerable: true,
  44832. configurable: true
  44833. });
  44834. // Methods
  44835. ActionManager.prototype.dispose = function () {
  44836. var index = this._scene._actionManagers.indexOf(this);
  44837. for (var i = 0; i < this.actions.length; i++) {
  44838. var action = this.actions[i];
  44839. ActionManager.Triggers[action.trigger]--;
  44840. if (ActionManager.Triggers[action.trigger] === 0) {
  44841. delete ActionManager.Triggers[action.trigger];
  44842. }
  44843. }
  44844. if (index > -1) {
  44845. this._scene._actionManagers.splice(index, 1);
  44846. }
  44847. };
  44848. ActionManager.prototype.getScene = function () {
  44849. return this._scene;
  44850. };
  44851. /**
  44852. * Does this action manager handles actions of any of the given triggers
  44853. * @param {number[]} triggers - the triggers to be tested
  44854. * @return {boolean} whether one (or more) of the triggers is handeled
  44855. */
  44856. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  44857. for (var index = 0; index < this.actions.length; index++) {
  44858. var action = this.actions[index];
  44859. if (triggers.indexOf(action.trigger) > -1) {
  44860. return true;
  44861. }
  44862. }
  44863. return false;
  44864. };
  44865. /**
  44866. * Does this action manager handles actions of a given trigger
  44867. * @param {number} trigger - the trigger to be tested
  44868. * @return {boolean} whether the trigger is handeled
  44869. */
  44870. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  44871. for (var index = 0; index < this.actions.length; index++) {
  44872. var action = this.actions[index];
  44873. if (action.trigger === trigger) {
  44874. return true;
  44875. }
  44876. }
  44877. return false;
  44878. };
  44879. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  44880. /**
  44881. * Does this action manager has pointer triggers
  44882. * @return {boolean} whether or not it has pointer triggers
  44883. */
  44884. get: function () {
  44885. for (var index = 0; index < this.actions.length; index++) {
  44886. var action = this.actions[index];
  44887. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  44888. return true;
  44889. }
  44890. }
  44891. return false;
  44892. },
  44893. enumerable: true,
  44894. configurable: true
  44895. });
  44896. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  44897. /**
  44898. * Does this action manager has pick triggers
  44899. * @return {boolean} whether or not it has pick triggers
  44900. */
  44901. get: function () {
  44902. for (var index = 0; index < this.actions.length; index++) {
  44903. var action = this.actions[index];
  44904. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  44905. return true;
  44906. }
  44907. }
  44908. return false;
  44909. },
  44910. enumerable: true,
  44911. configurable: true
  44912. });
  44913. Object.defineProperty(ActionManager, "HasTriggers", {
  44914. /**
  44915. * Does exist one action manager with at least one trigger
  44916. * @return {boolean} whether or not it exists one action manager with one trigger
  44917. **/
  44918. get: function () {
  44919. for (var t in ActionManager.Triggers) {
  44920. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44921. return true;
  44922. }
  44923. }
  44924. return false;
  44925. },
  44926. enumerable: true,
  44927. configurable: true
  44928. });
  44929. Object.defineProperty(ActionManager, "HasPickTriggers", {
  44930. /**
  44931. * Does exist one action manager with at least one pick trigger
  44932. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44933. **/
  44934. get: function () {
  44935. for (var t in ActionManager.Triggers) {
  44936. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44937. var t_int = parseInt(t);
  44938. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44939. return true;
  44940. }
  44941. }
  44942. }
  44943. return false;
  44944. },
  44945. enumerable: true,
  44946. configurable: true
  44947. });
  44948. /**
  44949. * Does exist one action manager that handles actions of a given trigger
  44950. * @param {number} trigger - the trigger to be tested
  44951. * @return {boolean} whether the trigger is handeled by at least one action manager
  44952. **/
  44953. ActionManager.HasSpecificTrigger = function (trigger) {
  44954. for (var t in ActionManager.Triggers) {
  44955. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44956. var t_int = parseInt(t);
  44957. if (t_int === trigger) {
  44958. return true;
  44959. }
  44960. }
  44961. }
  44962. return false;
  44963. };
  44964. /**
  44965. * Registers an action to this action manager
  44966. * @param {BABYLON.Action} action - the action to be registered
  44967. * @return {BABYLON.Action} the action amended (prepared) after registration
  44968. */
  44969. ActionManager.prototype.registerAction = function (action) {
  44970. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44971. if (this.getScene().actionManager !== this) {
  44972. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44973. return null;
  44974. }
  44975. }
  44976. this.actions.push(action);
  44977. if (ActionManager.Triggers[action.trigger]) {
  44978. ActionManager.Triggers[action.trigger]++;
  44979. }
  44980. else {
  44981. ActionManager.Triggers[action.trigger] = 1;
  44982. }
  44983. action._actionManager = this;
  44984. action._prepare();
  44985. return action;
  44986. };
  44987. /**
  44988. * Unregisters an action to this action manager
  44989. * @param action The action to be unregistered
  44990. * @return whether the action has been unregistered
  44991. */
  44992. ActionManager.prototype.unregisterAction = function (action) {
  44993. var index = this.actions.indexOf(action);
  44994. if (index !== -1) {
  44995. this.actions.splice(index, 1);
  44996. ActionManager.Triggers[action.trigger] -= 1;
  44997. if (ActionManager.Triggers[action.trigger] === 0) {
  44998. delete ActionManager.Triggers[action.trigger];
  44999. }
  45000. delete action._actionManager;
  45001. return true;
  45002. }
  45003. return false;
  45004. };
  45005. /**
  45006. * Process a specific trigger
  45007. * @param {number} trigger - the trigger to process
  45008. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45009. */
  45010. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45011. for (var index = 0; index < this.actions.length; index++) {
  45012. var action = this.actions[index];
  45013. if (action.trigger === trigger) {
  45014. if (evt) {
  45015. if (trigger === ActionManager.OnKeyUpTrigger
  45016. || trigger === ActionManager.OnKeyDownTrigger) {
  45017. var parameter = action.getTriggerParameter();
  45018. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45019. if (!parameter.toLowerCase) {
  45020. continue;
  45021. }
  45022. var lowerCase = parameter.toLowerCase();
  45023. if (lowerCase !== evt.sourceEvent.key) {
  45024. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45025. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45026. if (actualkey !== lowerCase) {
  45027. continue;
  45028. }
  45029. }
  45030. }
  45031. }
  45032. }
  45033. action._executeCurrent(evt);
  45034. }
  45035. }
  45036. };
  45037. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45038. var properties = propertyPath.split(".");
  45039. for (var index = 0; index < properties.length - 1; index++) {
  45040. target = target[properties[index]];
  45041. }
  45042. return target;
  45043. };
  45044. ActionManager.prototype._getProperty = function (propertyPath) {
  45045. var properties = propertyPath.split(".");
  45046. return properties[properties.length - 1];
  45047. };
  45048. ActionManager.prototype.serialize = function (name) {
  45049. var root = {
  45050. children: new Array(),
  45051. name: name,
  45052. type: 3,
  45053. properties: new Array() // Empty for root but required
  45054. };
  45055. for (var i = 0; i < this.actions.length; i++) {
  45056. var triggerObject = {
  45057. type: 0,
  45058. children: new Array(),
  45059. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45060. properties: new Array()
  45061. };
  45062. var triggerOptions = this.actions[i].triggerOptions;
  45063. if (triggerOptions && typeof triggerOptions !== "number") {
  45064. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45065. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45066. }
  45067. else {
  45068. var parameter = {};
  45069. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45070. if (triggerOptions.parameter.mesh) {
  45071. parameter._meshId = triggerOptions.parameter.mesh.id;
  45072. }
  45073. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45074. }
  45075. }
  45076. // Serialize child action, recursively
  45077. this.actions[i].serialize(triggerObject);
  45078. // Add serialized trigger
  45079. root.children.push(triggerObject);
  45080. }
  45081. return root;
  45082. };
  45083. ActionManager.Parse = function (parsedActions, object, scene) {
  45084. var actionManager = new ActionManager(scene);
  45085. if (object === null)
  45086. scene.actionManager = actionManager;
  45087. else
  45088. object.actionManager = actionManager;
  45089. // instanciate a new object
  45090. var instanciate = function (name, params) {
  45091. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  45092. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  45093. newInstance.constructor.apply(newInstance, params);
  45094. return newInstance;
  45095. };
  45096. var parseParameter = function (name, value, target, propertyPath) {
  45097. if (propertyPath === null) {
  45098. // String, boolean or float
  45099. var floatValue = parseFloat(value);
  45100. if (value === "true" || value === "false")
  45101. return value === "true";
  45102. else
  45103. return isNaN(floatValue) ? value : floatValue;
  45104. }
  45105. var effectiveTarget = propertyPath.split(".");
  45106. var values = value.split(",");
  45107. // Get effective Target
  45108. for (var i = 0; i < effectiveTarget.length; i++) {
  45109. target = target[effectiveTarget[i]];
  45110. }
  45111. // Return appropriate value with its type
  45112. if (typeof (target) === "boolean")
  45113. return values[0] === "true";
  45114. if (typeof (target) === "string")
  45115. return values[0];
  45116. // Parameters with multiple values such as Vector3 etc.
  45117. var split = new Array();
  45118. for (var i = 0; i < values.length; i++)
  45119. split.push(parseFloat(values[i]));
  45120. if (target instanceof BABYLON.Vector3)
  45121. return BABYLON.Vector3.FromArray(split);
  45122. if (target instanceof BABYLON.Vector4)
  45123. return BABYLON.Vector4.FromArray(split);
  45124. if (target instanceof BABYLON.Color3)
  45125. return BABYLON.Color3.FromArray(split);
  45126. if (target instanceof BABYLON.Color4)
  45127. return BABYLON.Color4.FromArray(split);
  45128. return parseFloat(values[0]);
  45129. };
  45130. // traverse graph per trigger
  45131. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45132. if (combineArray === void 0) { combineArray = null; }
  45133. if (parsedAction.detached)
  45134. return;
  45135. var parameters = new Array();
  45136. var target = null;
  45137. var propertyPath = null;
  45138. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45139. // Parameters
  45140. if (parsedAction.type === 2)
  45141. parameters.push(actionManager);
  45142. else
  45143. parameters.push(trigger);
  45144. if (combine) {
  45145. var actions = new Array();
  45146. for (var j = 0; j < parsedAction.combine.length; j++) {
  45147. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  45148. }
  45149. parameters.push(actions);
  45150. }
  45151. else {
  45152. for (var i = 0; i < parsedAction.properties.length; i++) {
  45153. var value = parsedAction.properties[i].value;
  45154. var name = parsedAction.properties[i].name;
  45155. var targetType = parsedAction.properties[i].targetType;
  45156. if (name === "target")
  45157. if (targetType !== null && targetType === "SceneProperties")
  45158. value = target = scene;
  45159. else
  45160. value = target = scene.getNodeByName(value);
  45161. else if (name === "parent")
  45162. value = scene.getNodeByName(value);
  45163. else if (name === "sound")
  45164. value = scene.getSoundByName(value);
  45165. else if (name !== "propertyPath") {
  45166. if (parsedAction.type === 2 && name === "operator")
  45167. value = BABYLON.ValueCondition[value];
  45168. else
  45169. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  45170. }
  45171. else {
  45172. propertyPath = value;
  45173. }
  45174. parameters.push(value);
  45175. }
  45176. }
  45177. if (combineArray === null) {
  45178. parameters.push(condition);
  45179. }
  45180. else {
  45181. parameters.push(null);
  45182. }
  45183. // If interpolate value action
  45184. if (parsedAction.name === "InterpolateValueAction") {
  45185. var param = parameters[parameters.length - 2];
  45186. parameters[parameters.length - 1] = param;
  45187. parameters[parameters.length - 2] = condition;
  45188. }
  45189. // Action or condition(s) and not CombineAction
  45190. var newAction = instanciate(parsedAction.name, parameters);
  45191. if (newAction instanceof BABYLON.Condition && condition !== null) {
  45192. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  45193. if (action)
  45194. action.then(nothing);
  45195. else
  45196. actionManager.registerAction(nothing);
  45197. action = nothing;
  45198. }
  45199. if (combineArray === null) {
  45200. if (newAction instanceof BABYLON.Condition) {
  45201. condition = newAction;
  45202. newAction = action;
  45203. }
  45204. else {
  45205. condition = null;
  45206. if (action)
  45207. action.then(newAction);
  45208. else
  45209. actionManager.registerAction(newAction);
  45210. }
  45211. }
  45212. else {
  45213. combineArray.push(newAction);
  45214. }
  45215. for (var i = 0; i < parsedAction.children.length; i++)
  45216. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45217. };
  45218. // triggers
  45219. for (var i = 0; i < parsedActions.children.length; i++) {
  45220. var triggerParams;
  45221. var trigger = parsedActions.children[i];
  45222. if (trigger.properties.length > 0) {
  45223. var param = trigger.properties[0].value;
  45224. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45225. if (value._meshId) {
  45226. value.mesh = scene.getMeshByID(value._meshId);
  45227. }
  45228. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45229. }
  45230. else
  45231. triggerParams = ActionManager[trigger.name];
  45232. for (var j = 0; j < trigger.children.length; j++) {
  45233. if (!trigger.detached)
  45234. traverse(trigger.children[j], triggerParams, null, null);
  45235. }
  45236. }
  45237. };
  45238. ActionManager.GetTriggerName = function (trigger) {
  45239. switch (trigger) {
  45240. case 0: return "NothingTrigger";
  45241. case 1: return "OnPickTrigger";
  45242. case 2: return "OnLeftPickTrigger";
  45243. case 3: return "OnRightPickTrigger";
  45244. case 4: return "OnCenterPickTrigger";
  45245. case 5: return "OnPickDownTrigger";
  45246. case 6: return "OnPickUpTrigger";
  45247. case 7: return "OnLongPressTrigger";
  45248. case 8: return "OnPointerOverTrigger";
  45249. case 9: return "OnPointerOutTrigger";
  45250. case 10: return "OnEveryFrameTrigger";
  45251. case 11: return "OnIntersectionEnterTrigger";
  45252. case 12: return "OnIntersectionExitTrigger";
  45253. case 13: return "OnKeyDownTrigger";
  45254. case 14: return "OnKeyUpTrigger";
  45255. case 15: return "OnPickOutTrigger";
  45256. default: return "";
  45257. }
  45258. };
  45259. // Statics
  45260. ActionManager._NothingTrigger = 0;
  45261. ActionManager._OnPickTrigger = 1;
  45262. ActionManager._OnLeftPickTrigger = 2;
  45263. ActionManager._OnRightPickTrigger = 3;
  45264. ActionManager._OnCenterPickTrigger = 4;
  45265. ActionManager._OnPickDownTrigger = 5;
  45266. ActionManager._OnDoublePickTrigger = 6;
  45267. ActionManager._OnPickUpTrigger = 7;
  45268. ActionManager._OnLongPressTrigger = 8;
  45269. ActionManager._OnPointerOverTrigger = 9;
  45270. ActionManager._OnPointerOutTrigger = 10;
  45271. ActionManager._OnEveryFrameTrigger = 11;
  45272. ActionManager._OnIntersectionEnterTrigger = 12;
  45273. ActionManager._OnIntersectionExitTrigger = 13;
  45274. ActionManager._OnKeyDownTrigger = 14;
  45275. ActionManager._OnKeyUpTrigger = 15;
  45276. ActionManager._OnPickOutTrigger = 16;
  45277. ActionManager.Triggers = {};
  45278. return ActionManager;
  45279. }());
  45280. BABYLON.ActionManager = ActionManager;
  45281. })(BABYLON || (BABYLON = {}));
  45282. //# sourceMappingURL=babylon.actionManager.js.map
  45283. var BABYLON;
  45284. (function (BABYLON) {
  45285. var InterpolateValueAction = /** @class */ (function (_super) {
  45286. __extends(InterpolateValueAction, _super);
  45287. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45288. if (duration === void 0) { duration = 1000; }
  45289. var _this = _super.call(this, triggerOptions, condition) || this;
  45290. _this.propertyPath = propertyPath;
  45291. _this.value = value;
  45292. _this.duration = duration;
  45293. _this.stopOtherAnimations = stopOtherAnimations;
  45294. _this.onInterpolationDone = onInterpolationDone;
  45295. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45296. _this._target = _this._effectiveTarget = target;
  45297. return _this;
  45298. }
  45299. InterpolateValueAction.prototype._prepare = function () {
  45300. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45301. this._property = this._getProperty(this.propertyPath);
  45302. };
  45303. InterpolateValueAction.prototype.execute = function () {
  45304. var _this = this;
  45305. var scene = this._actionManager.getScene();
  45306. var keys = [
  45307. {
  45308. frame: 0,
  45309. value: this._effectiveTarget[this._property]
  45310. }, {
  45311. frame: 100,
  45312. value: this.value
  45313. }
  45314. ];
  45315. var dataType;
  45316. if (typeof this.value === "number") {
  45317. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45318. }
  45319. else if (this.value instanceof BABYLON.Color3) {
  45320. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45321. }
  45322. else if (this.value instanceof BABYLON.Vector3) {
  45323. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45324. }
  45325. else if (this.value instanceof BABYLON.Matrix) {
  45326. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45327. }
  45328. else if (this.value instanceof BABYLON.Quaternion) {
  45329. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45330. }
  45331. else {
  45332. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45333. return;
  45334. }
  45335. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45336. animation.setKeys(keys);
  45337. if (this.stopOtherAnimations) {
  45338. scene.stopAnimation(this._effectiveTarget);
  45339. }
  45340. var wrapper = function () {
  45341. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45342. if (_this.onInterpolationDone) {
  45343. _this.onInterpolationDone();
  45344. }
  45345. };
  45346. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45347. };
  45348. InterpolateValueAction.prototype.serialize = function (parent) {
  45349. return _super.prototype._serialize.call(this, {
  45350. name: "InterpolateValueAction",
  45351. properties: [
  45352. BABYLON.Action._GetTargetProperty(this._target),
  45353. { name: "propertyPath", value: this.propertyPath },
  45354. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45355. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45356. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45357. ]
  45358. }, parent);
  45359. };
  45360. return InterpolateValueAction;
  45361. }(BABYLON.Action));
  45362. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45363. })(BABYLON || (BABYLON = {}));
  45364. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45365. var BABYLON;
  45366. (function (BABYLON) {
  45367. var SwitchBooleanAction = /** @class */ (function (_super) {
  45368. __extends(SwitchBooleanAction, _super);
  45369. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45370. var _this = _super.call(this, triggerOptions, condition) || this;
  45371. _this.propertyPath = propertyPath;
  45372. _this._target = _this._effectiveTarget = target;
  45373. return _this;
  45374. }
  45375. SwitchBooleanAction.prototype._prepare = function () {
  45376. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45377. this._property = this._getProperty(this.propertyPath);
  45378. };
  45379. SwitchBooleanAction.prototype.execute = function () {
  45380. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45381. };
  45382. SwitchBooleanAction.prototype.serialize = function (parent) {
  45383. return _super.prototype._serialize.call(this, {
  45384. name: "SwitchBooleanAction",
  45385. properties: [
  45386. BABYLON.Action._GetTargetProperty(this._target),
  45387. { name: "propertyPath", value: this.propertyPath }
  45388. ]
  45389. }, parent);
  45390. };
  45391. return SwitchBooleanAction;
  45392. }(BABYLON.Action));
  45393. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45394. var SetStateAction = /** @class */ (function (_super) {
  45395. __extends(SetStateAction, _super);
  45396. function SetStateAction(triggerOptions, target, value, condition) {
  45397. var _this = _super.call(this, triggerOptions, condition) || this;
  45398. _this.value = value;
  45399. _this._target = target;
  45400. return _this;
  45401. }
  45402. SetStateAction.prototype.execute = function () {
  45403. this._target.state = this.value;
  45404. };
  45405. SetStateAction.prototype.serialize = function (parent) {
  45406. return _super.prototype._serialize.call(this, {
  45407. name: "SetStateAction",
  45408. properties: [
  45409. BABYLON.Action._GetTargetProperty(this._target),
  45410. { name: "value", value: this.value }
  45411. ]
  45412. }, parent);
  45413. };
  45414. return SetStateAction;
  45415. }(BABYLON.Action));
  45416. BABYLON.SetStateAction = SetStateAction;
  45417. var SetValueAction = /** @class */ (function (_super) {
  45418. __extends(SetValueAction, _super);
  45419. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45420. var _this = _super.call(this, triggerOptions, condition) || this;
  45421. _this.propertyPath = propertyPath;
  45422. _this.value = value;
  45423. _this._target = _this._effectiveTarget = target;
  45424. return _this;
  45425. }
  45426. SetValueAction.prototype._prepare = function () {
  45427. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45428. this._property = this._getProperty(this.propertyPath);
  45429. };
  45430. SetValueAction.prototype.execute = function () {
  45431. this._effectiveTarget[this._property] = this.value;
  45432. if (this._target.markAsDirty) {
  45433. this._target.markAsDirty(this._property);
  45434. }
  45435. };
  45436. SetValueAction.prototype.serialize = function (parent) {
  45437. return _super.prototype._serialize.call(this, {
  45438. name: "SetValueAction",
  45439. properties: [
  45440. BABYLON.Action._GetTargetProperty(this._target),
  45441. { name: "propertyPath", value: this.propertyPath },
  45442. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45443. ]
  45444. }, parent);
  45445. };
  45446. return SetValueAction;
  45447. }(BABYLON.Action));
  45448. BABYLON.SetValueAction = SetValueAction;
  45449. var IncrementValueAction = /** @class */ (function (_super) {
  45450. __extends(IncrementValueAction, _super);
  45451. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45452. var _this = _super.call(this, triggerOptions, condition) || this;
  45453. _this.propertyPath = propertyPath;
  45454. _this.value = value;
  45455. _this._target = _this._effectiveTarget = target;
  45456. return _this;
  45457. }
  45458. IncrementValueAction.prototype._prepare = function () {
  45459. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45460. this._property = this._getProperty(this.propertyPath);
  45461. if (typeof this._effectiveTarget[this._property] !== "number") {
  45462. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45463. }
  45464. };
  45465. IncrementValueAction.prototype.execute = function () {
  45466. this._effectiveTarget[this._property] += this.value;
  45467. if (this._target.markAsDirty) {
  45468. this._target.markAsDirty(this._property);
  45469. }
  45470. };
  45471. IncrementValueAction.prototype.serialize = function (parent) {
  45472. return _super.prototype._serialize.call(this, {
  45473. name: "IncrementValueAction",
  45474. properties: [
  45475. BABYLON.Action._GetTargetProperty(this._target),
  45476. { name: "propertyPath", value: this.propertyPath },
  45477. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45478. ]
  45479. }, parent);
  45480. };
  45481. return IncrementValueAction;
  45482. }(BABYLON.Action));
  45483. BABYLON.IncrementValueAction = IncrementValueAction;
  45484. var PlayAnimationAction = /** @class */ (function (_super) {
  45485. __extends(PlayAnimationAction, _super);
  45486. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  45487. var _this = _super.call(this, triggerOptions, condition) || this;
  45488. _this.from = from;
  45489. _this.to = to;
  45490. _this.loop = loop;
  45491. _this._target = target;
  45492. return _this;
  45493. }
  45494. PlayAnimationAction.prototype._prepare = function () {
  45495. };
  45496. PlayAnimationAction.prototype.execute = function () {
  45497. var scene = this._actionManager.getScene();
  45498. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  45499. };
  45500. PlayAnimationAction.prototype.serialize = function (parent) {
  45501. return _super.prototype._serialize.call(this, {
  45502. name: "PlayAnimationAction",
  45503. properties: [
  45504. BABYLON.Action._GetTargetProperty(this._target),
  45505. { name: "from", value: String(this.from) },
  45506. { name: "to", value: String(this.to) },
  45507. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  45508. ]
  45509. }, parent);
  45510. };
  45511. return PlayAnimationAction;
  45512. }(BABYLON.Action));
  45513. BABYLON.PlayAnimationAction = PlayAnimationAction;
  45514. var StopAnimationAction = /** @class */ (function (_super) {
  45515. __extends(StopAnimationAction, _super);
  45516. function StopAnimationAction(triggerOptions, target, condition) {
  45517. var _this = _super.call(this, triggerOptions, condition) || this;
  45518. _this._target = target;
  45519. return _this;
  45520. }
  45521. StopAnimationAction.prototype._prepare = function () {
  45522. };
  45523. StopAnimationAction.prototype.execute = function () {
  45524. var scene = this._actionManager.getScene();
  45525. scene.stopAnimation(this._target);
  45526. };
  45527. StopAnimationAction.prototype.serialize = function (parent) {
  45528. return _super.prototype._serialize.call(this, {
  45529. name: "StopAnimationAction",
  45530. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  45531. }, parent);
  45532. };
  45533. return StopAnimationAction;
  45534. }(BABYLON.Action));
  45535. BABYLON.StopAnimationAction = StopAnimationAction;
  45536. var DoNothingAction = /** @class */ (function (_super) {
  45537. __extends(DoNothingAction, _super);
  45538. function DoNothingAction(triggerOptions, condition) {
  45539. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  45540. return _super.call(this, triggerOptions, condition) || this;
  45541. }
  45542. DoNothingAction.prototype.execute = function () {
  45543. };
  45544. DoNothingAction.prototype.serialize = function (parent) {
  45545. return _super.prototype._serialize.call(this, {
  45546. name: "DoNothingAction",
  45547. properties: []
  45548. }, parent);
  45549. };
  45550. return DoNothingAction;
  45551. }(BABYLON.Action));
  45552. BABYLON.DoNothingAction = DoNothingAction;
  45553. var CombineAction = /** @class */ (function (_super) {
  45554. __extends(CombineAction, _super);
  45555. function CombineAction(triggerOptions, children, condition) {
  45556. var _this = _super.call(this, triggerOptions, condition) || this;
  45557. _this.children = children;
  45558. return _this;
  45559. }
  45560. CombineAction.prototype._prepare = function () {
  45561. for (var index = 0; index < this.children.length; index++) {
  45562. this.children[index]._actionManager = this._actionManager;
  45563. this.children[index]._prepare();
  45564. }
  45565. };
  45566. CombineAction.prototype.execute = function (evt) {
  45567. for (var index = 0; index < this.children.length; index++) {
  45568. this.children[index].execute(evt);
  45569. }
  45570. };
  45571. CombineAction.prototype.serialize = function (parent) {
  45572. var serializationObject = _super.prototype._serialize.call(this, {
  45573. name: "CombineAction",
  45574. properties: [],
  45575. combine: []
  45576. }, parent);
  45577. for (var i = 0; i < this.children.length; i++) {
  45578. serializationObject.combine.push(this.children[i].serialize(null));
  45579. }
  45580. return serializationObject;
  45581. };
  45582. return CombineAction;
  45583. }(BABYLON.Action));
  45584. BABYLON.CombineAction = CombineAction;
  45585. var ExecuteCodeAction = /** @class */ (function (_super) {
  45586. __extends(ExecuteCodeAction, _super);
  45587. function ExecuteCodeAction(triggerOptions, func, condition) {
  45588. var _this = _super.call(this, triggerOptions, condition) || this;
  45589. _this.func = func;
  45590. return _this;
  45591. }
  45592. ExecuteCodeAction.prototype.execute = function (evt) {
  45593. this.func(evt);
  45594. };
  45595. return ExecuteCodeAction;
  45596. }(BABYLON.Action));
  45597. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  45598. var SetParentAction = /** @class */ (function (_super) {
  45599. __extends(SetParentAction, _super);
  45600. function SetParentAction(triggerOptions, target, parent, condition) {
  45601. var _this = _super.call(this, triggerOptions, condition) || this;
  45602. _this._target = target;
  45603. _this._parent = parent;
  45604. return _this;
  45605. }
  45606. SetParentAction.prototype._prepare = function () {
  45607. };
  45608. SetParentAction.prototype.execute = function () {
  45609. if (this._target.parent === this._parent) {
  45610. return;
  45611. }
  45612. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  45613. invertParentWorldMatrix.invert();
  45614. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  45615. this._target.parent = this._parent;
  45616. };
  45617. SetParentAction.prototype.serialize = function (parent) {
  45618. return _super.prototype._serialize.call(this, {
  45619. name: "SetParentAction",
  45620. properties: [
  45621. BABYLON.Action._GetTargetProperty(this._target),
  45622. BABYLON.Action._GetTargetProperty(this._parent),
  45623. ]
  45624. }, parent);
  45625. };
  45626. return SetParentAction;
  45627. }(BABYLON.Action));
  45628. BABYLON.SetParentAction = SetParentAction;
  45629. var PlaySoundAction = /** @class */ (function (_super) {
  45630. __extends(PlaySoundAction, _super);
  45631. function PlaySoundAction(triggerOptions, sound, condition) {
  45632. var _this = _super.call(this, triggerOptions, condition) || this;
  45633. _this._sound = sound;
  45634. return _this;
  45635. }
  45636. PlaySoundAction.prototype._prepare = function () {
  45637. };
  45638. PlaySoundAction.prototype.execute = function () {
  45639. if (this._sound !== undefined)
  45640. this._sound.play();
  45641. };
  45642. PlaySoundAction.prototype.serialize = function (parent) {
  45643. return _super.prototype._serialize.call(this, {
  45644. name: "PlaySoundAction",
  45645. properties: [{ name: "sound", value: this._sound.name }]
  45646. }, parent);
  45647. };
  45648. return PlaySoundAction;
  45649. }(BABYLON.Action));
  45650. BABYLON.PlaySoundAction = PlaySoundAction;
  45651. var StopSoundAction = /** @class */ (function (_super) {
  45652. __extends(StopSoundAction, _super);
  45653. function StopSoundAction(triggerOptions, sound, condition) {
  45654. var _this = _super.call(this, triggerOptions, condition) || this;
  45655. _this._sound = sound;
  45656. return _this;
  45657. }
  45658. StopSoundAction.prototype._prepare = function () {
  45659. };
  45660. StopSoundAction.prototype.execute = function () {
  45661. if (this._sound !== undefined)
  45662. this._sound.stop();
  45663. };
  45664. StopSoundAction.prototype.serialize = function (parent) {
  45665. return _super.prototype._serialize.call(this, {
  45666. name: "StopSoundAction",
  45667. properties: [{ name: "sound", value: this._sound.name }]
  45668. }, parent);
  45669. };
  45670. return StopSoundAction;
  45671. }(BABYLON.Action));
  45672. BABYLON.StopSoundAction = StopSoundAction;
  45673. })(BABYLON || (BABYLON = {}));
  45674. //# sourceMappingURL=babylon.directActions.js.map
  45675. var BABYLON;
  45676. (function (BABYLON) {
  45677. var SpriteManager = /** @class */ (function () {
  45678. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  45679. if (epsilon === void 0) { epsilon = 0.01; }
  45680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45681. this.name = name;
  45682. this.sprites = new Array();
  45683. this.renderingGroupId = 0;
  45684. this.layerMask = 0x0FFFFFFF;
  45685. this.fogEnabled = true;
  45686. this.isPickable = false;
  45687. /**
  45688. * An event triggered when the manager is disposed.
  45689. * @type {BABYLON.Observable}
  45690. */
  45691. this.onDisposeObservable = new BABYLON.Observable();
  45692. this._vertexBuffers = {};
  45693. this._capacity = capacity;
  45694. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  45695. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45696. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45697. if (cellSize.width && cellSize.height) {
  45698. this.cellWidth = cellSize.width;
  45699. this.cellHeight = cellSize.height;
  45700. }
  45701. else if (cellSize !== undefined) {
  45702. this.cellWidth = cellSize;
  45703. this.cellHeight = cellSize;
  45704. }
  45705. else {
  45706. return;
  45707. }
  45708. this._epsilon = epsilon;
  45709. this._scene = scene;
  45710. this._scene.spriteManagers.push(this);
  45711. var indices = [];
  45712. var index = 0;
  45713. for (var count = 0; count < capacity; count++) {
  45714. indices.push(index);
  45715. indices.push(index + 1);
  45716. indices.push(index + 2);
  45717. indices.push(index);
  45718. indices.push(index + 2);
  45719. indices.push(index + 3);
  45720. index += 4;
  45721. }
  45722. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  45723. // VBO
  45724. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  45725. this._vertexData = new Float32Array(capacity * 16 * 4);
  45726. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  45727. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  45728. var options = this._buffer.createVertexBuffer("options", 4, 4);
  45729. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  45730. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  45731. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45732. this._vertexBuffers["options"] = options;
  45733. this._vertexBuffers["cellInfo"] = cellInfo;
  45734. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45735. // Effects
  45736. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  45737. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  45738. }
  45739. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  45740. set: function (callback) {
  45741. if (this._onDisposeObserver) {
  45742. this.onDisposeObservable.remove(this._onDisposeObserver);
  45743. }
  45744. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45745. },
  45746. enumerable: true,
  45747. configurable: true
  45748. });
  45749. Object.defineProperty(SpriteManager.prototype, "texture", {
  45750. get: function () {
  45751. return this._spriteTexture;
  45752. },
  45753. set: function (value) {
  45754. this._spriteTexture = value;
  45755. },
  45756. enumerable: true,
  45757. configurable: true
  45758. });
  45759. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  45760. var arrayOffset = index * 16;
  45761. if (offsetX === 0)
  45762. offsetX = this._epsilon;
  45763. else if (offsetX === 1)
  45764. offsetX = 1 - this._epsilon;
  45765. if (offsetY === 0)
  45766. offsetY = this._epsilon;
  45767. else if (offsetY === 1)
  45768. offsetY = 1 - this._epsilon;
  45769. this._vertexData[arrayOffset] = sprite.position.x;
  45770. this._vertexData[arrayOffset + 1] = sprite.position.y;
  45771. this._vertexData[arrayOffset + 2] = sprite.position.z;
  45772. this._vertexData[arrayOffset + 3] = sprite.angle;
  45773. this._vertexData[arrayOffset + 4] = sprite.width;
  45774. this._vertexData[arrayOffset + 5] = sprite.height;
  45775. this._vertexData[arrayOffset + 6] = offsetX;
  45776. this._vertexData[arrayOffset + 7] = offsetY;
  45777. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  45778. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  45779. var offset = (sprite.cellIndex / rowSize) >> 0;
  45780. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  45781. this._vertexData[arrayOffset + 11] = offset;
  45782. // Color
  45783. this._vertexData[arrayOffset + 12] = sprite.color.r;
  45784. this._vertexData[arrayOffset + 13] = sprite.color.g;
  45785. this._vertexData[arrayOffset + 14] = sprite.color.b;
  45786. this._vertexData[arrayOffset + 15] = sprite.color.a;
  45787. };
  45788. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  45789. var count = Math.min(this._capacity, this.sprites.length);
  45790. var min = BABYLON.Vector3.Zero();
  45791. var max = BABYLON.Vector3.Zero();
  45792. var distance = Number.MAX_VALUE;
  45793. var currentSprite = null;
  45794. var cameraSpacePosition = BABYLON.Vector3.Zero();
  45795. var cameraView = camera.getViewMatrix();
  45796. for (var index = 0; index < count; index++) {
  45797. var sprite = this.sprites[index];
  45798. if (!sprite) {
  45799. continue;
  45800. }
  45801. if (predicate) {
  45802. if (!predicate(sprite)) {
  45803. continue;
  45804. }
  45805. }
  45806. else if (!sprite.isPickable) {
  45807. continue;
  45808. }
  45809. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  45810. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  45811. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  45812. if (ray.intersectsBoxMinMax(min, max)) {
  45813. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  45814. if (distance > currentDistance) {
  45815. distance = currentDistance;
  45816. currentSprite = sprite;
  45817. if (fastCheck) {
  45818. break;
  45819. }
  45820. }
  45821. }
  45822. }
  45823. if (currentSprite) {
  45824. var result = new BABYLON.PickingInfo();
  45825. result.hit = true;
  45826. result.pickedSprite = currentSprite;
  45827. result.distance = distance;
  45828. return result;
  45829. }
  45830. return null;
  45831. };
  45832. SpriteManager.prototype.render = function () {
  45833. // Check
  45834. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  45835. return;
  45836. var engine = this._scene.getEngine();
  45837. var baseSize = this._spriteTexture.getBaseSize();
  45838. // Sprites
  45839. var deltaTime = engine.getDeltaTime();
  45840. var max = Math.min(this._capacity, this.sprites.length);
  45841. var rowSize = baseSize.width / this.cellWidth;
  45842. var offset = 0;
  45843. for (var index = 0; index < max; index++) {
  45844. var sprite = this.sprites[index];
  45845. if (!sprite) {
  45846. continue;
  45847. }
  45848. sprite._animate(deltaTime);
  45849. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  45850. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  45851. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  45852. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  45853. }
  45854. this._buffer.update(this._vertexData);
  45855. // Render
  45856. var effect = this._effectBase;
  45857. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45858. effect = this._effectFog;
  45859. }
  45860. engine.enableEffect(effect);
  45861. var viewMatrix = this._scene.getViewMatrix();
  45862. effect.setTexture("diffuseSampler", this._spriteTexture);
  45863. effect.setMatrix("view", viewMatrix);
  45864. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  45865. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  45866. // Fog
  45867. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  45868. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  45869. effect.setColor3("vFogColor", this._scene.fogColor);
  45870. }
  45871. // VBOs
  45872. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  45873. // Draw order
  45874. engine.setDepthFunctionToLessOrEqual();
  45875. effect.setBool("alphaTest", true);
  45876. engine.setColorWrite(false);
  45877. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  45878. engine.setColorWrite(true);
  45879. effect.setBool("alphaTest", false);
  45880. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  45881. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  45882. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  45883. };
  45884. SpriteManager.prototype.dispose = function () {
  45885. if (this._buffer) {
  45886. this._buffer.dispose();
  45887. this._buffer = null;
  45888. }
  45889. if (this._indexBuffer) {
  45890. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45891. this._indexBuffer = null;
  45892. }
  45893. if (this._spriteTexture) {
  45894. this._spriteTexture.dispose();
  45895. this._spriteTexture = null;
  45896. }
  45897. // Remove from scene
  45898. var index = this._scene.spriteManagers.indexOf(this);
  45899. this._scene.spriteManagers.splice(index, 1);
  45900. // Callback
  45901. this.onDisposeObservable.notifyObservers(this);
  45902. this.onDisposeObservable.clear();
  45903. };
  45904. return SpriteManager;
  45905. }());
  45906. BABYLON.SpriteManager = SpriteManager;
  45907. })(BABYLON || (BABYLON = {}));
  45908. //# sourceMappingURL=babylon.spriteManager.js.map
  45909. var BABYLON;
  45910. (function (BABYLON) {
  45911. var Sprite = /** @class */ (function () {
  45912. function Sprite(name, manager) {
  45913. this.name = name;
  45914. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45915. this.width = 1.0;
  45916. this.height = 1.0;
  45917. this.angle = 0;
  45918. this.cellIndex = 0;
  45919. this.invertU = 0;
  45920. this.invertV = 0;
  45921. this.animations = new Array();
  45922. this.isPickable = false;
  45923. this._animationStarted = false;
  45924. this._loopAnimation = false;
  45925. this._fromIndex = 0;
  45926. this._toIndex = 0;
  45927. this._delay = 0;
  45928. this._direction = 1;
  45929. this._time = 0;
  45930. this._manager = manager;
  45931. this._manager.sprites.push(this);
  45932. this.position = BABYLON.Vector3.Zero();
  45933. }
  45934. Object.defineProperty(Sprite.prototype, "size", {
  45935. get: function () {
  45936. return this.width;
  45937. },
  45938. set: function (value) {
  45939. this.width = value;
  45940. this.height = value;
  45941. },
  45942. enumerable: true,
  45943. configurable: true
  45944. });
  45945. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  45946. this._fromIndex = from;
  45947. this._toIndex = to;
  45948. this._loopAnimation = loop;
  45949. this._delay = delay;
  45950. this._animationStarted = true;
  45951. this._direction = from < to ? 1 : -1;
  45952. this.cellIndex = from;
  45953. this._time = 0;
  45954. this._onAnimationEnd = onAnimationEnd;
  45955. };
  45956. Sprite.prototype.stopAnimation = function () {
  45957. this._animationStarted = false;
  45958. };
  45959. Sprite.prototype._animate = function (deltaTime) {
  45960. if (!this._animationStarted)
  45961. return;
  45962. this._time += deltaTime;
  45963. if (this._time > this._delay) {
  45964. this._time = this._time % this._delay;
  45965. this.cellIndex += this._direction;
  45966. if (this.cellIndex > this._toIndex) {
  45967. if (this._loopAnimation) {
  45968. this.cellIndex = this._fromIndex;
  45969. }
  45970. else {
  45971. this.cellIndex = this._toIndex;
  45972. this._animationStarted = false;
  45973. if (this._onAnimationEnd) {
  45974. this._onAnimationEnd();
  45975. }
  45976. if (this.disposeWhenFinishedAnimating) {
  45977. this.dispose();
  45978. }
  45979. }
  45980. }
  45981. }
  45982. };
  45983. Sprite.prototype.dispose = function () {
  45984. for (var i = 0; i < this._manager.sprites.length; i++) {
  45985. if (this._manager.sprites[i] == this) {
  45986. this._manager.sprites.splice(i, 1);
  45987. }
  45988. }
  45989. };
  45990. return Sprite;
  45991. }());
  45992. BABYLON.Sprite = Sprite;
  45993. })(BABYLON || (BABYLON = {}));
  45994. //# sourceMappingURL=babylon.sprite.js.map
  45995. var BABYLON;
  45996. (function (BABYLON) {
  45997. var IntersectionInfo = /** @class */ (function () {
  45998. function IntersectionInfo(bu, bv, distance) {
  45999. this.bu = bu;
  46000. this.bv = bv;
  46001. this.distance = distance;
  46002. this.faceId = 0;
  46003. this.subMeshId = 0;
  46004. }
  46005. return IntersectionInfo;
  46006. }());
  46007. BABYLON.IntersectionInfo = IntersectionInfo;
  46008. var PickingInfo = /** @class */ (function () {
  46009. function PickingInfo() {
  46010. this.hit = false;
  46011. this.distance = 0;
  46012. this.pickedPoint = null;
  46013. this.pickedMesh = null;
  46014. this.bu = 0;
  46015. this.bv = 0;
  46016. this.faceId = -1;
  46017. this.subMeshId = 0;
  46018. this.pickedSprite = null;
  46019. }
  46020. // Methods
  46021. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  46022. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  46023. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  46024. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46025. return null;
  46026. }
  46027. var indices = this.pickedMesh.getIndices();
  46028. if (!indices) {
  46029. return null;
  46030. }
  46031. var result;
  46032. if (useVerticesNormals) {
  46033. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46034. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  46035. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  46036. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  46037. normal0 = normal0.scale(this.bu);
  46038. normal1 = normal1.scale(this.bv);
  46039. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  46040. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  46041. }
  46042. else {
  46043. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46044. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  46045. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  46046. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  46047. var p1p2 = vertex1.subtract(vertex2);
  46048. var p3p2 = vertex3.subtract(vertex2);
  46049. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  46050. }
  46051. if (useWorldCoordinates) {
  46052. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  46053. }
  46054. return BABYLON.Vector3.Normalize(result);
  46055. };
  46056. PickingInfo.prototype.getTextureCoordinates = function () {
  46057. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46058. return null;
  46059. }
  46060. var indices = this.pickedMesh.getIndices();
  46061. if (!indices) {
  46062. return null;
  46063. }
  46064. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46065. if (!uvs) {
  46066. return null;
  46067. }
  46068. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  46069. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  46070. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  46071. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  46072. uv1 = uv1.scale(this.bu);
  46073. uv2 = uv2.scale(this.bv);
  46074. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  46075. };
  46076. return PickingInfo;
  46077. }());
  46078. BABYLON.PickingInfo = PickingInfo;
  46079. })(BABYLON || (BABYLON = {}));
  46080. //# sourceMappingURL=babylon.pickingInfo.js.map
  46081. var BABYLON;
  46082. (function (BABYLON) {
  46083. var Ray = /** @class */ (function () {
  46084. function Ray(origin, direction, length) {
  46085. if (length === void 0) { length = Number.MAX_VALUE; }
  46086. this.origin = origin;
  46087. this.direction = direction;
  46088. this.length = length;
  46089. }
  46090. // Methods
  46091. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  46092. var d = 0.0;
  46093. var maxValue = Number.MAX_VALUE;
  46094. var inv;
  46095. var min;
  46096. var max;
  46097. var temp;
  46098. if (Math.abs(this.direction.x) < 0.0000001) {
  46099. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  46100. return false;
  46101. }
  46102. }
  46103. else {
  46104. inv = 1.0 / this.direction.x;
  46105. min = (minimum.x - this.origin.x) * inv;
  46106. max = (maximum.x - this.origin.x) * inv;
  46107. if (max === -Infinity) {
  46108. max = Infinity;
  46109. }
  46110. if (min > max) {
  46111. temp = min;
  46112. min = max;
  46113. max = temp;
  46114. }
  46115. d = Math.max(min, d);
  46116. maxValue = Math.min(max, maxValue);
  46117. if (d > maxValue) {
  46118. return false;
  46119. }
  46120. }
  46121. if (Math.abs(this.direction.y) < 0.0000001) {
  46122. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  46123. return false;
  46124. }
  46125. }
  46126. else {
  46127. inv = 1.0 / this.direction.y;
  46128. min = (minimum.y - this.origin.y) * inv;
  46129. max = (maximum.y - this.origin.y) * inv;
  46130. if (max === -Infinity) {
  46131. max = Infinity;
  46132. }
  46133. if (min > max) {
  46134. temp = min;
  46135. min = max;
  46136. max = temp;
  46137. }
  46138. d = Math.max(min, d);
  46139. maxValue = Math.min(max, maxValue);
  46140. if (d > maxValue) {
  46141. return false;
  46142. }
  46143. }
  46144. if (Math.abs(this.direction.z) < 0.0000001) {
  46145. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  46146. return false;
  46147. }
  46148. }
  46149. else {
  46150. inv = 1.0 / this.direction.z;
  46151. min = (minimum.z - this.origin.z) * inv;
  46152. max = (maximum.z - this.origin.z) * inv;
  46153. if (max === -Infinity) {
  46154. max = Infinity;
  46155. }
  46156. if (min > max) {
  46157. temp = min;
  46158. min = max;
  46159. max = temp;
  46160. }
  46161. d = Math.max(min, d);
  46162. maxValue = Math.min(max, maxValue);
  46163. if (d > maxValue) {
  46164. return false;
  46165. }
  46166. }
  46167. return true;
  46168. };
  46169. Ray.prototype.intersectsBox = function (box) {
  46170. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  46171. };
  46172. Ray.prototype.intersectsSphere = function (sphere) {
  46173. var x = sphere.center.x - this.origin.x;
  46174. var y = sphere.center.y - this.origin.y;
  46175. var z = sphere.center.z - this.origin.z;
  46176. var pyth = (x * x) + (y * y) + (z * z);
  46177. var rr = sphere.radius * sphere.radius;
  46178. if (pyth <= rr) {
  46179. return true;
  46180. }
  46181. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  46182. if (dot < 0.0) {
  46183. return false;
  46184. }
  46185. var temp = pyth - (dot * dot);
  46186. return temp <= rr;
  46187. };
  46188. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  46189. if (!this._edge1) {
  46190. this._edge1 = BABYLON.Vector3.Zero();
  46191. this._edge2 = BABYLON.Vector3.Zero();
  46192. this._pvec = BABYLON.Vector3.Zero();
  46193. this._tvec = BABYLON.Vector3.Zero();
  46194. this._qvec = BABYLON.Vector3.Zero();
  46195. }
  46196. vertex1.subtractToRef(vertex0, this._edge1);
  46197. vertex2.subtractToRef(vertex0, this._edge2);
  46198. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46199. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46200. if (det === 0) {
  46201. return null;
  46202. }
  46203. var invdet = 1 / det;
  46204. this.origin.subtractToRef(vertex0, this._tvec);
  46205. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46206. if (bu < 0 || bu > 1.0) {
  46207. return null;
  46208. }
  46209. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46210. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46211. if (bv < 0 || bu + bv > 1.0) {
  46212. return null;
  46213. }
  46214. //check if the distance is longer than the predefined length.
  46215. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46216. if (distance > this.length) {
  46217. return null;
  46218. }
  46219. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46220. };
  46221. Ray.prototype.intersectsPlane = function (plane) {
  46222. var distance;
  46223. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46224. if (Math.abs(result1) < 9.99999997475243E-07) {
  46225. return null;
  46226. }
  46227. else {
  46228. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46229. distance = (-plane.d - result2) / result1;
  46230. if (distance < 0.0) {
  46231. if (distance < -9.99999997475243E-07) {
  46232. return null;
  46233. }
  46234. else {
  46235. return 0;
  46236. }
  46237. }
  46238. return distance;
  46239. }
  46240. };
  46241. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46242. var tm = BABYLON.Tmp.Matrix[0];
  46243. mesh.getWorldMatrix().invertToRef(tm);
  46244. if (this._tmpRay) {
  46245. Ray.TransformToRef(this, tm, this._tmpRay);
  46246. }
  46247. else {
  46248. this._tmpRay = Ray.Transform(this, tm);
  46249. }
  46250. return mesh.intersects(this._tmpRay, fastCheck);
  46251. };
  46252. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46253. if (results) {
  46254. results.length = 0;
  46255. }
  46256. else {
  46257. results = [];
  46258. }
  46259. for (var i = 0; i < meshes.length; i++) {
  46260. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46261. if (pickInfo.hit) {
  46262. results.push(pickInfo);
  46263. }
  46264. }
  46265. results.sort(this._comparePickingInfo);
  46266. return results;
  46267. };
  46268. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46269. if (pickingInfoA.distance < pickingInfoB.distance) {
  46270. return -1;
  46271. }
  46272. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46273. return 1;
  46274. }
  46275. else {
  46276. return 0;
  46277. }
  46278. };
  46279. /**
  46280. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46281. * @param sega the first point of the segment to test the intersection against
  46282. * @param segb the second point of the segment to test the intersection against
  46283. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46284. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46285. */
  46286. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46287. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46288. var u = segb.subtract(sega);
  46289. var v = rsegb.subtract(this.origin);
  46290. var w = sega.subtract(this.origin);
  46291. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46292. var b = BABYLON.Vector3.Dot(u, v);
  46293. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46294. var d = BABYLON.Vector3.Dot(u, w);
  46295. var e = BABYLON.Vector3.Dot(v, w);
  46296. var D = a * c - b * b; // always >= 0
  46297. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46298. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46299. // compute the line parameters of the two closest points
  46300. if (D < Ray.smallnum) {
  46301. sN = 0.0; // force using point P0 on segment S1
  46302. sD = 1.0; // to prevent possible division by 0.0 later
  46303. tN = e;
  46304. tD = c;
  46305. }
  46306. else {
  46307. sN = (b * e - c * d);
  46308. tN = (a * e - b * d);
  46309. if (sN < 0.0) {
  46310. sN = 0.0;
  46311. tN = e;
  46312. tD = c;
  46313. }
  46314. else if (sN > sD) {
  46315. sN = sD;
  46316. tN = e + b;
  46317. tD = c;
  46318. }
  46319. }
  46320. if (tN < 0.0) {
  46321. tN = 0.0;
  46322. // recompute sc for this edge
  46323. if (-d < 0.0) {
  46324. sN = 0.0;
  46325. }
  46326. else if (-d > a)
  46327. sN = sD;
  46328. else {
  46329. sN = -d;
  46330. sD = a;
  46331. }
  46332. }
  46333. else if (tN > tD) {
  46334. tN = tD;
  46335. // recompute sc for this edge
  46336. if ((-d + b) < 0.0) {
  46337. sN = 0;
  46338. }
  46339. else if ((-d + b) > a) {
  46340. sN = sD;
  46341. }
  46342. else {
  46343. sN = (-d + b);
  46344. sD = a;
  46345. }
  46346. }
  46347. // finally do the division to get sc and tc
  46348. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46349. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46350. // get the difference of the two closest points
  46351. var qtc = v.multiplyByFloats(tc, tc, tc);
  46352. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46353. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46354. if (isIntersected) {
  46355. return qtc.length();
  46356. }
  46357. return -1;
  46358. };
  46359. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46360. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46361. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46362. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46363. this.direction.normalize();
  46364. return this;
  46365. };
  46366. // Statics
  46367. Ray.Zero = function () {
  46368. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46369. };
  46370. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46371. var result = Ray.Zero();
  46372. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46373. };
  46374. /**
  46375. * 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
  46376. * transformed to the given world matrix.
  46377. * @param origin The origin point
  46378. * @param end The end point
  46379. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46380. */
  46381. Ray.CreateNewFromTo = function (origin, end, world) {
  46382. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46383. var direction = end.subtract(origin);
  46384. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46385. direction.normalize();
  46386. return Ray.Transform(new Ray(origin, direction, length), world);
  46387. };
  46388. Ray.Transform = function (ray, matrix) {
  46389. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46390. Ray.TransformToRef(ray, matrix, result);
  46391. return result;
  46392. };
  46393. Ray.TransformToRef = function (ray, matrix, result) {
  46394. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46395. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46396. result.length = ray.length;
  46397. var dir = result.direction;
  46398. var len = dir.length();
  46399. if (!(len === 0 || len === 1)) {
  46400. var num = 1.0 / len;
  46401. dir.x *= num;
  46402. dir.y *= num;
  46403. dir.z *= num;
  46404. result.length *= len;
  46405. }
  46406. };
  46407. Ray.smallnum = 0.00000001;
  46408. Ray.rayl = 10e8;
  46409. return Ray;
  46410. }());
  46411. BABYLON.Ray = Ray;
  46412. })(BABYLON || (BABYLON = {}));
  46413. //# sourceMappingURL=babylon.ray.js.map
  46414. var BABYLON;
  46415. (function (BABYLON) {
  46416. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46417. if (boxMin.x > sphereCenter.x + sphereRadius)
  46418. return false;
  46419. if (sphereCenter.x - sphereRadius > boxMax.x)
  46420. return false;
  46421. if (boxMin.y > sphereCenter.y + sphereRadius)
  46422. return false;
  46423. if (sphereCenter.y - sphereRadius > boxMax.y)
  46424. return false;
  46425. if (boxMin.z > sphereCenter.z + sphereRadius)
  46426. return false;
  46427. if (sphereCenter.z - sphereRadius > boxMax.z)
  46428. return false;
  46429. return true;
  46430. };
  46431. var getLowestRoot = (function () {
  46432. var result = { root: 0, found: false };
  46433. return function (a, b, c, maxR) {
  46434. result.root = 0;
  46435. result.found = false;
  46436. var determinant = b * b - 4.0 * a * c;
  46437. if (determinant < 0)
  46438. return result;
  46439. var sqrtD = Math.sqrt(determinant);
  46440. var r1 = (-b - sqrtD) / (2.0 * a);
  46441. var r2 = (-b + sqrtD) / (2.0 * a);
  46442. if (r1 > r2) {
  46443. var temp = r2;
  46444. r2 = r1;
  46445. r1 = temp;
  46446. }
  46447. if (r1 > 0 && r1 < maxR) {
  46448. result.root = r1;
  46449. result.found = true;
  46450. return result;
  46451. }
  46452. if (r2 > 0 && r2 < maxR) {
  46453. result.root = r2;
  46454. result.found = true;
  46455. return result;
  46456. }
  46457. return result;
  46458. };
  46459. })();
  46460. var Collider = /** @class */ (function () {
  46461. function Collider() {
  46462. this._collisionPoint = BABYLON.Vector3.Zero();
  46463. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  46464. this._tempVector = BABYLON.Vector3.Zero();
  46465. this._tempVector2 = BABYLON.Vector3.Zero();
  46466. this._tempVector3 = BABYLON.Vector3.Zero();
  46467. this._tempVector4 = BABYLON.Vector3.Zero();
  46468. this._edge = BABYLON.Vector3.Zero();
  46469. this._baseToVertex = BABYLON.Vector3.Zero();
  46470. this._destinationPoint = BABYLON.Vector3.Zero();
  46471. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  46472. this._displacementVector = BABYLON.Vector3.Zero();
  46473. this._radius = BABYLON.Vector3.One();
  46474. this._retry = 0;
  46475. this._basePointWorld = BABYLON.Vector3.Zero();
  46476. this._velocityWorld = BABYLON.Vector3.Zero();
  46477. this._normalizedVelocity = BABYLON.Vector3.Zero();
  46478. this._collisionMask = -1;
  46479. }
  46480. Object.defineProperty(Collider.prototype, "collisionMask", {
  46481. get: function () {
  46482. return this._collisionMask;
  46483. },
  46484. set: function (mask) {
  46485. this._collisionMask = !isNaN(mask) ? mask : -1;
  46486. },
  46487. enumerable: true,
  46488. configurable: true
  46489. });
  46490. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  46491. /**
  46492. * Gets the plane normal used to compute the sliding response (in local space)
  46493. */
  46494. get: function () {
  46495. return this._slidePlaneNormal;
  46496. },
  46497. enumerable: true,
  46498. configurable: true
  46499. });
  46500. // Methods
  46501. Collider.prototype._initialize = function (source, dir, e) {
  46502. this._velocity = dir;
  46503. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  46504. this._basePoint = source;
  46505. source.multiplyToRef(this._radius, this._basePointWorld);
  46506. dir.multiplyToRef(this._radius, this._velocityWorld);
  46507. this._velocityWorldLength = this._velocityWorld.length();
  46508. this._epsilon = e;
  46509. this.collisionFound = false;
  46510. };
  46511. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  46512. pa.subtractToRef(point, this._tempVector);
  46513. pb.subtractToRef(point, this._tempVector2);
  46514. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  46515. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46516. if (d < 0)
  46517. return false;
  46518. pc.subtractToRef(point, this._tempVector3);
  46519. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  46520. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46521. if (d < 0)
  46522. return false;
  46523. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  46524. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46525. return d >= 0;
  46526. };
  46527. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  46528. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  46529. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  46530. if (distance > this._velocityWorldLength + max + sphereRadius) {
  46531. return false;
  46532. }
  46533. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  46534. return false;
  46535. return true;
  46536. };
  46537. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  46538. var t0;
  46539. var embeddedInPlane = false;
  46540. //defensive programming, actually not needed.
  46541. if (!trianglePlaneArray) {
  46542. trianglePlaneArray = [];
  46543. }
  46544. if (!trianglePlaneArray[faceIndex]) {
  46545. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  46546. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  46547. }
  46548. var trianglePlane = trianglePlaneArray[faceIndex];
  46549. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  46550. return;
  46551. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  46552. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  46553. if (normalDotVelocity == 0) {
  46554. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  46555. return;
  46556. embeddedInPlane = true;
  46557. t0 = 0;
  46558. }
  46559. else {
  46560. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46561. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46562. if (t0 > t1) {
  46563. var temp = t1;
  46564. t1 = t0;
  46565. t0 = temp;
  46566. }
  46567. if (t0 > 1.0 || t1 < 0.0)
  46568. return;
  46569. if (t0 < 0)
  46570. t0 = 0;
  46571. if (t0 > 1.0)
  46572. t0 = 1.0;
  46573. }
  46574. this._collisionPoint.copyFromFloats(0, 0, 0);
  46575. var found = false;
  46576. var t = 1.0;
  46577. if (!embeddedInPlane) {
  46578. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  46579. this._velocity.scaleToRef(t0, this._tempVector);
  46580. this._planeIntersectionPoint.addInPlace(this._tempVector);
  46581. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  46582. found = true;
  46583. t = t0;
  46584. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  46585. }
  46586. }
  46587. if (!found) {
  46588. var velocitySquaredLength = this._velocity.lengthSquared();
  46589. var a = velocitySquaredLength;
  46590. this._basePoint.subtractToRef(p1, this._tempVector);
  46591. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46592. var c = this._tempVector.lengthSquared() - 1.0;
  46593. var lowestRoot = getLowestRoot(a, b, c, t);
  46594. if (lowestRoot.found) {
  46595. t = lowestRoot.root;
  46596. found = true;
  46597. this._collisionPoint.copyFrom(p1);
  46598. }
  46599. this._basePoint.subtractToRef(p2, this._tempVector);
  46600. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46601. c = this._tempVector.lengthSquared() - 1.0;
  46602. lowestRoot = getLowestRoot(a, b, c, t);
  46603. if (lowestRoot.found) {
  46604. t = lowestRoot.root;
  46605. found = true;
  46606. this._collisionPoint.copyFrom(p2);
  46607. }
  46608. this._basePoint.subtractToRef(p3, this._tempVector);
  46609. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46610. c = this._tempVector.lengthSquared() - 1.0;
  46611. lowestRoot = getLowestRoot(a, b, c, t);
  46612. if (lowestRoot.found) {
  46613. t = lowestRoot.root;
  46614. found = true;
  46615. this._collisionPoint.copyFrom(p3);
  46616. }
  46617. p2.subtractToRef(p1, this._edge);
  46618. p1.subtractToRef(this._basePoint, this._baseToVertex);
  46619. var edgeSquaredLength = this._edge.lengthSquared();
  46620. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46621. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46622. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46623. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46624. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46625. lowestRoot = getLowestRoot(a, b, c, t);
  46626. if (lowestRoot.found) {
  46627. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46628. if (f >= 0.0 && f <= 1.0) {
  46629. t = lowestRoot.root;
  46630. found = true;
  46631. this._edge.scaleInPlace(f);
  46632. p1.addToRef(this._edge, this._collisionPoint);
  46633. }
  46634. }
  46635. p3.subtractToRef(p2, this._edge);
  46636. p2.subtractToRef(this._basePoint, this._baseToVertex);
  46637. edgeSquaredLength = this._edge.lengthSquared();
  46638. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46639. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46640. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46641. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46642. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46643. lowestRoot = getLowestRoot(a, b, c, t);
  46644. if (lowestRoot.found) {
  46645. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46646. if (f >= 0.0 && f <= 1.0) {
  46647. t = lowestRoot.root;
  46648. found = true;
  46649. this._edge.scaleInPlace(f);
  46650. p2.addToRef(this._edge, this._collisionPoint);
  46651. }
  46652. }
  46653. p1.subtractToRef(p3, this._edge);
  46654. p3.subtractToRef(this._basePoint, this._baseToVertex);
  46655. edgeSquaredLength = this._edge.lengthSquared();
  46656. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46657. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46658. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46659. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46660. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46661. lowestRoot = getLowestRoot(a, b, c, t);
  46662. if (lowestRoot.found) {
  46663. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46664. if (f >= 0.0 && f <= 1.0) {
  46665. t = lowestRoot.root;
  46666. found = true;
  46667. this._edge.scaleInPlace(f);
  46668. p3.addToRef(this._edge, this._collisionPoint);
  46669. }
  46670. }
  46671. }
  46672. if (found) {
  46673. var distToCollision = t * this._velocity.length();
  46674. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  46675. if (!this.intersectionPoint) {
  46676. this.intersectionPoint = this._collisionPoint.clone();
  46677. }
  46678. else {
  46679. this.intersectionPoint.copyFrom(this._collisionPoint);
  46680. }
  46681. this._nearestDistance = distToCollision;
  46682. this.collisionFound = true;
  46683. }
  46684. }
  46685. };
  46686. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  46687. for (var i = indexStart; i < indexEnd; i += 3) {
  46688. var p1 = pts[indices[i] - decal];
  46689. var p2 = pts[indices[i + 1] - decal];
  46690. var p3 = pts[indices[i + 2] - decal];
  46691. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  46692. }
  46693. };
  46694. Collider.prototype._getResponse = function (pos, vel) {
  46695. pos.addToRef(vel, this._destinationPoint);
  46696. vel.scaleInPlace((this._nearestDistance / vel.length()));
  46697. this._basePoint.addToRef(vel, pos);
  46698. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  46699. this._slidePlaneNormal.normalize();
  46700. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  46701. pos.addInPlace(this._displacementVector);
  46702. this.intersectionPoint.addInPlace(this._displacementVector);
  46703. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  46704. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  46705. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  46706. };
  46707. return Collider;
  46708. }());
  46709. BABYLON.Collider = Collider;
  46710. })(BABYLON || (BABYLON = {}));
  46711. //# sourceMappingURL=babylon.collider.js.map
  46712. var BABYLON;
  46713. (function (BABYLON) {
  46714. //WebWorker code will be inserted to this variable.
  46715. BABYLON.CollisionWorker = "";
  46716. var WorkerTaskType;
  46717. (function (WorkerTaskType) {
  46718. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  46719. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  46720. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  46721. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  46722. var WorkerReplyType;
  46723. (function (WorkerReplyType) {
  46724. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  46725. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  46726. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  46727. var CollisionCoordinatorWorker = /** @class */ (function () {
  46728. function CollisionCoordinatorWorker() {
  46729. var _this = this;
  46730. this._scaledPosition = BABYLON.Vector3.Zero();
  46731. this._scaledVelocity = BABYLON.Vector3.Zero();
  46732. this.onMeshUpdated = function (transformNode) {
  46733. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  46734. };
  46735. this.onGeometryUpdated = function (geometry) {
  46736. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  46737. };
  46738. this._afterRender = function () {
  46739. if (!_this._init)
  46740. return;
  46741. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  46742. return;
  46743. }
  46744. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  46745. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  46746. if (_this._runningUpdated > 4) {
  46747. return;
  46748. }
  46749. ++_this._runningUpdated;
  46750. var payload = {
  46751. updatedMeshes: _this._addUpdateMeshesList,
  46752. updatedGeometries: _this._addUpdateGeometriesList,
  46753. removedGeometries: _this._toRemoveGeometryArray,
  46754. removedMeshes: _this._toRemoveMeshesArray
  46755. };
  46756. var message = {
  46757. payload: payload,
  46758. taskType: WorkerTaskType.UPDATE
  46759. };
  46760. var serializable = [];
  46761. for (var id in payload.updatedGeometries) {
  46762. if (payload.updatedGeometries.hasOwnProperty(id)) {
  46763. //prepare transferables
  46764. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  46765. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  46766. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  46767. }
  46768. }
  46769. _this._worker.postMessage(message, serializable);
  46770. _this._addUpdateMeshesList = {};
  46771. _this._addUpdateGeometriesList = {};
  46772. _this._toRemoveGeometryArray = [];
  46773. _this._toRemoveMeshesArray = [];
  46774. };
  46775. this._onMessageFromWorker = function (e) {
  46776. var returnData = e.data;
  46777. if (returnData.error != WorkerReplyType.SUCCESS) {
  46778. //TODO what errors can be returned from the worker?
  46779. BABYLON.Tools.Warn("error returned from worker!");
  46780. return;
  46781. }
  46782. switch (returnData.taskType) {
  46783. case WorkerTaskType.INIT:
  46784. _this._init = true;
  46785. //Update the worked with ALL of the scene's current state
  46786. _this._scene.meshes.forEach(function (mesh) {
  46787. _this.onMeshAdded(mesh);
  46788. });
  46789. _this._scene.getGeometries().forEach(function (geometry) {
  46790. _this.onGeometryAdded(geometry);
  46791. });
  46792. break;
  46793. case WorkerTaskType.UPDATE:
  46794. _this._runningUpdated--;
  46795. break;
  46796. case WorkerTaskType.COLLIDE:
  46797. var returnPayload = returnData.payload;
  46798. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  46799. return;
  46800. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  46801. if (callback) {
  46802. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  46803. if (mesh) {
  46804. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  46805. }
  46806. }
  46807. //cleanup
  46808. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  46809. break;
  46810. }
  46811. };
  46812. this._collisionsCallbackArray = [];
  46813. this._init = false;
  46814. this._runningUpdated = 0;
  46815. this._addUpdateMeshesList = {};
  46816. this._addUpdateGeometriesList = {};
  46817. this._toRemoveGeometryArray = [];
  46818. this._toRemoveMeshesArray = [];
  46819. }
  46820. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46821. if (!this._init)
  46822. return;
  46823. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  46824. return;
  46825. position.divideToRef(collider._radius, this._scaledPosition);
  46826. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46827. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  46828. var payload = {
  46829. collider: {
  46830. position: this._scaledPosition.asArray(),
  46831. velocity: this._scaledVelocity.asArray(),
  46832. radius: collider._radius.asArray()
  46833. },
  46834. collisionId: collisionIndex,
  46835. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  46836. maximumRetry: maximumRetry
  46837. };
  46838. var message = {
  46839. payload: payload,
  46840. taskType: WorkerTaskType.COLLIDE
  46841. };
  46842. this._worker.postMessage(message);
  46843. };
  46844. CollisionCoordinatorWorker.prototype.init = function (scene) {
  46845. this._scene = scene;
  46846. this._scene.registerAfterRender(this._afterRender);
  46847. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  46848. this._worker = new Worker(workerUrl);
  46849. this._worker.onmessage = this._onMessageFromWorker;
  46850. var message = {
  46851. payload: {},
  46852. taskType: WorkerTaskType.INIT
  46853. };
  46854. this._worker.postMessage(message);
  46855. };
  46856. CollisionCoordinatorWorker.prototype.destroy = function () {
  46857. this._scene.unregisterAfterRender(this._afterRender);
  46858. this._worker.terminate();
  46859. };
  46860. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  46861. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  46862. this.onMeshUpdated(mesh);
  46863. };
  46864. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  46865. this._toRemoveMeshesArray.push(mesh.uniqueId);
  46866. };
  46867. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  46868. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  46869. geometry.onGeometryUpdated = this.onGeometryUpdated;
  46870. this.onGeometryUpdated(geometry);
  46871. };
  46872. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  46873. this._toRemoveGeometryArray.push(geometry.id);
  46874. };
  46875. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  46876. var submeshes = [];
  46877. if (mesh.subMeshes) {
  46878. submeshes = mesh.subMeshes.map(function (sm, idx) {
  46879. var boundingInfo = sm.getBoundingInfo();
  46880. return {
  46881. position: idx,
  46882. verticesStart: sm.verticesStart,
  46883. verticesCount: sm.verticesCount,
  46884. indexStart: sm.indexStart,
  46885. indexCount: sm.indexCount,
  46886. hasMaterial: !!sm.getMaterial(),
  46887. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  46888. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  46889. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  46890. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  46891. };
  46892. });
  46893. }
  46894. var geometryId = null;
  46895. if (mesh instanceof BABYLON.Mesh) {
  46896. var geometry = mesh.geometry;
  46897. geometryId = geometry ? geometry.id : null;
  46898. }
  46899. else if (mesh instanceof BABYLON.InstancedMesh) {
  46900. var geometry = mesh.sourceMesh.geometry;
  46901. geometryId = geometry ? geometry.id : null;
  46902. }
  46903. var boundingInfo = mesh.getBoundingInfo();
  46904. return {
  46905. uniqueId: mesh.uniqueId,
  46906. id: mesh.id,
  46907. name: mesh.name,
  46908. geometryId: geometryId,
  46909. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  46910. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  46911. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  46912. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  46913. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  46914. subMeshes: submeshes,
  46915. checkCollisions: mesh.checkCollisions
  46916. };
  46917. };
  46918. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  46919. return {
  46920. id: geometry.id,
  46921. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  46922. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  46923. indices: new Uint32Array(geometry.getIndices() || []),
  46924. };
  46925. };
  46926. return CollisionCoordinatorWorker;
  46927. }());
  46928. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  46929. var CollisionCoordinatorLegacy = /** @class */ (function () {
  46930. function CollisionCoordinatorLegacy() {
  46931. this._scaledPosition = BABYLON.Vector3.Zero();
  46932. this._scaledVelocity = BABYLON.Vector3.Zero();
  46933. this._finalPosition = BABYLON.Vector3.Zero();
  46934. }
  46935. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46936. position.divideToRef(collider._radius, this._scaledPosition);
  46937. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46938. collider.collidedMesh = null;
  46939. collider._retry = 0;
  46940. collider._initialVelocity = this._scaledVelocity;
  46941. collider._initialPosition = this._scaledPosition;
  46942. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  46943. this._finalPosition.multiplyInPlace(collider._radius);
  46944. //run the callback
  46945. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  46946. };
  46947. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  46948. this._scene = scene;
  46949. };
  46950. CollisionCoordinatorLegacy.prototype.destroy = function () {
  46951. //Legacy need no destruction method.
  46952. };
  46953. //No update in legacy mode
  46954. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  46955. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  46956. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  46957. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  46958. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  46959. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  46960. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  46961. if (excludedMesh === void 0) { excludedMesh = null; }
  46962. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  46963. if (collider._retry >= maximumRetry) {
  46964. finalPosition.copyFrom(position);
  46965. return;
  46966. }
  46967. // Check if this is a mesh else camera or -1
  46968. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46969. collider._initialize(position, velocity, closeDistance);
  46970. // Check all meshes
  46971. for (var index = 0; index < this._scene.meshes.length; index++) {
  46972. var mesh = this._scene.meshes[index];
  46973. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46974. mesh._checkCollision(collider);
  46975. }
  46976. }
  46977. if (!collider.collisionFound) {
  46978. position.addToRef(velocity, finalPosition);
  46979. return;
  46980. }
  46981. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46982. collider._getResponse(position, velocity);
  46983. }
  46984. if (velocity.length() <= closeDistance) {
  46985. finalPosition.copyFrom(position);
  46986. return;
  46987. }
  46988. collider._retry++;
  46989. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46990. };
  46991. return CollisionCoordinatorLegacy;
  46992. }());
  46993. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46994. })(BABYLON || (BABYLON = {}));
  46995. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46996. var BABYLON;
  46997. (function (BABYLON) {
  46998. /**
  46999. * A particle represents one of the element emitted by a particle system.
  47000. * This is mainly define by its coordinates, direction, velocity and age.
  47001. */
  47002. var Particle = /** @class */ (function () {
  47003. /**
  47004. * Creates a new instance of @see Particle
  47005. * @param particleSystem the particle system the particle belongs to
  47006. */
  47007. function Particle(particleSystem) {
  47008. this.particleSystem = particleSystem;
  47009. /**
  47010. * The world position of the particle in the scene.
  47011. */
  47012. this.position = BABYLON.Vector3.Zero();
  47013. /**
  47014. * The world direction of the particle in the scene.
  47015. */
  47016. this.direction = BABYLON.Vector3.Zero();
  47017. /**
  47018. * The color of the particle.
  47019. */
  47020. this.color = new BABYLON.Color4(0, 0, 0, 0);
  47021. /**
  47022. * The color change of the particle per step.
  47023. */
  47024. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  47025. /**
  47026. * Defines how long will the life of the particle be.
  47027. */
  47028. this.lifeTime = 1.0;
  47029. /**
  47030. * The current age of the particle.
  47031. */
  47032. this.age = 0;
  47033. /**
  47034. * The current size of the particle.
  47035. */
  47036. this.size = 0;
  47037. /**
  47038. * The current angle of the particle.
  47039. */
  47040. this.angle = 0;
  47041. /**
  47042. * Defines how fast is the angle changing.
  47043. */
  47044. this.angularSpeed = 0;
  47045. /**
  47046. * Defines the cell index used by the particle to be rendered from a sprite.
  47047. */
  47048. this.cellIndex = 0;
  47049. this._currentFrameCounter = 0;
  47050. if (!this.particleSystem.isAnimationSheetEnabled) {
  47051. return;
  47052. }
  47053. this.cellIndex = this.particleSystem.startSpriteCellID;
  47054. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  47055. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  47056. }
  47057. else {
  47058. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  47059. }
  47060. }
  47061. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  47062. // (ageOffset / scaledUpdateSpeed) / available cells
  47063. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  47064. this._currentFrameCounter += scaledUpdateSpeed;
  47065. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  47066. this._currentFrameCounter = 0;
  47067. this.cellIndex++;
  47068. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47069. this.cellIndex = this.particleSystem.endSpriteCellID;
  47070. }
  47071. }
  47072. };
  47073. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  47074. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  47075. this.cellIndex++;
  47076. this._currentFrameCounter = 0;
  47077. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47078. if (this.particleSystem.spriteCellLoop) {
  47079. this.cellIndex = this.particleSystem.startSpriteCellID;
  47080. }
  47081. else {
  47082. this.cellIndex = this.particleSystem.endSpriteCellID;
  47083. }
  47084. }
  47085. }
  47086. else {
  47087. this._currentFrameCounter++;
  47088. }
  47089. };
  47090. /**
  47091. * Copy the properties of particle to another one.
  47092. * @param other the particle to copy the information to.
  47093. */
  47094. Particle.prototype.copyTo = function (other) {
  47095. other.position.copyFrom(this.position);
  47096. other.direction.copyFrom(this.direction);
  47097. other.color.copyFrom(this.color);
  47098. other.colorStep.copyFrom(this.colorStep);
  47099. other.lifeTime = this.lifeTime;
  47100. other.age = this.age;
  47101. other.size = this.size;
  47102. other.angle = this.angle;
  47103. other.angularSpeed = this.angularSpeed;
  47104. other.particleSystem = this.particleSystem;
  47105. other.cellIndex = this.cellIndex;
  47106. };
  47107. return Particle;
  47108. }());
  47109. BABYLON.Particle = Particle;
  47110. })(BABYLON || (BABYLON = {}));
  47111. //# sourceMappingURL=babylon.particle.js.map
  47112. var BABYLON;
  47113. (function (BABYLON) {
  47114. /**
  47115. * This represents a particle system in Babylon.
  47116. * 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.
  47117. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  47118. * @example https://doc.babylonjs.com/babylon101/particles
  47119. */
  47120. var ParticleSystem = /** @class */ (function () {
  47121. /**
  47122. * Instantiates a particle system.
  47123. * 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.
  47124. * @param name The name of the particle system
  47125. * @param capacity The max number of particles alive at the same time
  47126. * @param scene The scene the particle system belongs to
  47127. * @param customEffect a custom effect used to change the way particles are rendered by default
  47128. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  47129. * @param epsilon Offset used to render the particles
  47130. */
  47131. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  47132. if (customEffect === void 0) { customEffect = null; }
  47133. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  47134. if (epsilon === void 0) { epsilon = 0.01; }
  47135. var _this = this;
  47136. /**
  47137. * List of animations used by the particle system.
  47138. */
  47139. this.animations = [];
  47140. /**
  47141. * The rendering group used by the Particle system to chose when to render.
  47142. */
  47143. this.renderingGroupId = 0;
  47144. /**
  47145. * The emitter represents the Mesh or position we are attaching the particle system to.
  47146. */
  47147. this.emitter = null;
  47148. /**
  47149. * The density of particles, the rate of particle flow
  47150. */
  47151. this.emitRate = 10;
  47152. /**
  47153. * If you want to launch only a few particles at once, that can be done, as well.
  47154. */
  47155. this.manualEmitCount = -1;
  47156. /**
  47157. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47158. */
  47159. this.updateSpeed = 0.01;
  47160. /**
  47161. * The amount of time the particle system is running (depends of the overall speed above).
  47162. */
  47163. this.targetStopDuration = 0;
  47164. /**
  47165. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  47166. */
  47167. this.disposeOnStop = false;
  47168. /**
  47169. * Minimum power of emitting particles.
  47170. */
  47171. this.minEmitPower = 1;
  47172. /**
  47173. * Maximum power of emitting particles.
  47174. */
  47175. this.maxEmitPower = 1;
  47176. /**
  47177. * Minimum life time of emitting particles.
  47178. */
  47179. this.minLifeTime = 1;
  47180. /**
  47181. * Maximum life time of emitting particles.
  47182. */
  47183. this.maxLifeTime = 1;
  47184. /**
  47185. * Minimum Size of emitting particles.
  47186. */
  47187. this.minSize = 1;
  47188. /**
  47189. * Maximum Size of emitting particles.
  47190. */
  47191. this.maxSize = 1;
  47192. /**
  47193. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  47194. */
  47195. this.minAngularSpeed = 0;
  47196. /**
  47197. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  47198. */
  47199. this.maxAngularSpeed = 0;
  47200. /**
  47201. * The layer mask we are rendering the particles through.
  47202. */
  47203. this.layerMask = 0x0FFFFFFF;
  47204. /**
  47205. * This can help using your own shader to render the particle system.
  47206. * The according effect will be created
  47207. */
  47208. this.customShader = null;
  47209. /**
  47210. * By default particle system starts as soon as they are created. This prevents the
  47211. * automatic start to happen and let you decide when to start emitting particles.
  47212. */
  47213. this.preventAutoStart = false;
  47214. /**
  47215. * Callback triggered when the particle animation is ending.
  47216. */
  47217. this.onAnimationEnd = null;
  47218. /**
  47219. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47220. */
  47221. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47222. /**
  47223. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47224. * to override the particles.
  47225. */
  47226. this.forceDepthWrite = false;
  47227. /**
  47228. * You can use gravity if you want to give an orientation to your particles.
  47229. */
  47230. this.gravity = BABYLON.Vector3.Zero();
  47231. /**
  47232. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47233. */
  47234. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47235. /**
  47236. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47237. */
  47238. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47239. /**
  47240. * 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.
  47241. */
  47242. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47243. /**
  47244. * 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.
  47245. */
  47246. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47247. /**
  47248. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47249. */
  47250. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47251. /**
  47252. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47253. */
  47254. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47255. /**
  47256. * Color the particle will have at the end of its lifetime.
  47257. */
  47258. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47259. /**
  47260. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47261. */
  47262. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47263. /**
  47264. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47265. */
  47266. this.spriteCellLoop = true;
  47267. /**
  47268. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47269. */
  47270. this.spriteCellChangeSpeed = 0;
  47271. /**
  47272. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47273. */
  47274. this.startSpriteCellID = 0;
  47275. /**
  47276. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47277. */
  47278. this.endSpriteCellID = 0;
  47279. /**
  47280. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47281. */
  47282. this.spriteCellWidth = 0;
  47283. /**
  47284. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47285. */
  47286. this.spriteCellHeight = 0;
  47287. /**
  47288. * An event triggered when the system is disposed.
  47289. */
  47290. this.onDisposeObservable = new BABYLON.Observable();
  47291. this._particles = new Array();
  47292. this._stockParticles = new Array();
  47293. this._newPartsExcess = 0;
  47294. this._vertexBuffers = {};
  47295. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47296. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47297. this._scaledDirection = BABYLON.Vector3.Zero();
  47298. this._scaledGravity = BABYLON.Vector3.Zero();
  47299. this._currentRenderId = -1;
  47300. this._started = false;
  47301. this._stopped = false;
  47302. this._actualFrame = 0;
  47303. this._vertexBufferSize = 11;
  47304. this._appendParticleVertexes = null;
  47305. this.id = name;
  47306. this.name = name;
  47307. this._capacity = capacity;
  47308. this._epsilon = epsilon;
  47309. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47310. if (isAnimationSheetEnabled) {
  47311. this._vertexBufferSize = 12;
  47312. }
  47313. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47314. this._customEffect = customEffect;
  47315. scene.particleSystems.push(this);
  47316. this._createIndexBuffer();
  47317. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47318. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47319. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47320. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47321. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47322. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47323. if (this._isAnimationSheetEnabled) {
  47324. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47325. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47326. }
  47327. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47328. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47329. this._vertexBuffers["options"] = options;
  47330. // Default behaviors
  47331. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47332. this.updateFunction = function (particles) {
  47333. for (var index = 0; index < particles.length; index++) {
  47334. var particle = particles[index];
  47335. particle.age += _this._scaledUpdateSpeed;
  47336. if (particle.age >= particle.lifeTime) {
  47337. _this.recycleParticle(particle);
  47338. index--;
  47339. continue;
  47340. }
  47341. else {
  47342. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47343. particle.color.addInPlace(_this._scaledColorStep);
  47344. if (particle.color.a < 0)
  47345. particle.color.a = 0;
  47346. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47347. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47348. particle.position.addInPlace(_this._scaledDirection);
  47349. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47350. particle.direction.addInPlace(_this._scaledGravity);
  47351. if (_this._isAnimationSheetEnabled) {
  47352. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47353. }
  47354. }
  47355. }
  47356. };
  47357. }
  47358. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47359. /**
  47360. * Sets a callback that will be triggered when the system is disposed.
  47361. */
  47362. set: function (callback) {
  47363. if (this._onDisposeObserver) {
  47364. this.onDisposeObservable.remove(this._onDisposeObserver);
  47365. }
  47366. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47367. },
  47368. enumerable: true,
  47369. configurable: true
  47370. });
  47371. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47372. /**
  47373. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47374. */
  47375. get: function () {
  47376. return this._isAnimationSheetEnabled;
  47377. },
  47378. enumerable: true,
  47379. configurable: true
  47380. });
  47381. ParticleSystem.prototype._createIndexBuffer = function () {
  47382. var indices = [];
  47383. var index = 0;
  47384. for (var count = 0; count < this._capacity; count++) {
  47385. indices.push(index);
  47386. indices.push(index + 1);
  47387. indices.push(index + 2);
  47388. indices.push(index);
  47389. indices.push(index + 2);
  47390. indices.push(index + 3);
  47391. index += 4;
  47392. }
  47393. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47394. };
  47395. /**
  47396. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47397. * Its lifetime will start back at 0.
  47398. * @param particle The particle to recycle
  47399. */
  47400. ParticleSystem.prototype.recycleParticle = function (particle) {
  47401. var lastParticle = this._particles.pop();
  47402. if (lastParticle !== particle) {
  47403. lastParticle.copyTo(particle);
  47404. this._stockParticles.push(lastParticle);
  47405. }
  47406. };
  47407. /**
  47408. * Gets the maximum number of particles active at the same time.
  47409. * @returns The max number of active particles.
  47410. */
  47411. ParticleSystem.prototype.getCapacity = function () {
  47412. return this._capacity;
  47413. };
  47414. /**
  47415. * Gets Wether there are still active particles in the system.
  47416. * @returns True if it is alive, otherwise false.
  47417. */
  47418. ParticleSystem.prototype.isAlive = function () {
  47419. return this._alive;
  47420. };
  47421. /**
  47422. * Gets Wether the system has been started.
  47423. * @returns True if it has been started, otherwise false.
  47424. */
  47425. ParticleSystem.prototype.isStarted = function () {
  47426. return this._started;
  47427. };
  47428. /**
  47429. * Starts the particle system and begins to emit.
  47430. */
  47431. ParticleSystem.prototype.start = function () {
  47432. this._started = true;
  47433. this._stopped = false;
  47434. this._actualFrame = 0;
  47435. };
  47436. /**
  47437. * Stops the particle system.
  47438. */
  47439. ParticleSystem.prototype.stop = function () {
  47440. this._stopped = true;
  47441. };
  47442. /**
  47443. * @ignore (for internal use only)
  47444. */
  47445. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47446. var offset = index * this._vertexBufferSize;
  47447. this._vertexData[offset] = particle.position.x;
  47448. this._vertexData[offset + 1] = particle.position.y;
  47449. this._vertexData[offset + 2] = particle.position.z;
  47450. this._vertexData[offset + 3] = particle.color.r;
  47451. this._vertexData[offset + 4] = particle.color.g;
  47452. this._vertexData[offset + 5] = particle.color.b;
  47453. this._vertexData[offset + 6] = particle.color.a;
  47454. this._vertexData[offset + 7] = particle.angle;
  47455. this._vertexData[offset + 8] = particle.size;
  47456. this._vertexData[offset + 9] = offsetX;
  47457. this._vertexData[offset + 10] = offsetY;
  47458. };
  47459. /**
  47460. * @ignore (for internal use only)
  47461. */
  47462. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  47463. if (offsetX === 0)
  47464. offsetX = this._epsilon;
  47465. else if (offsetX === 1)
  47466. offsetX = 1 - this._epsilon;
  47467. if (offsetY === 0)
  47468. offsetY = this._epsilon;
  47469. else if (offsetY === 1)
  47470. offsetY = 1 - this._epsilon;
  47471. var offset = index * this._vertexBufferSize;
  47472. this._vertexData[offset] = particle.position.x;
  47473. this._vertexData[offset + 1] = particle.position.y;
  47474. this._vertexData[offset + 2] = particle.position.z;
  47475. this._vertexData[offset + 3] = particle.color.r;
  47476. this._vertexData[offset + 4] = particle.color.g;
  47477. this._vertexData[offset + 5] = particle.color.b;
  47478. this._vertexData[offset + 6] = particle.color.a;
  47479. this._vertexData[offset + 7] = particle.angle;
  47480. this._vertexData[offset + 8] = particle.size;
  47481. this._vertexData[offset + 9] = offsetX;
  47482. this._vertexData[offset + 10] = offsetY;
  47483. this._vertexData[offset + 11] = particle.cellIndex;
  47484. };
  47485. ParticleSystem.prototype._update = function (newParticles) {
  47486. // Update current
  47487. this._alive = this._particles.length > 0;
  47488. this.updateFunction(this._particles);
  47489. // Add new ones
  47490. var worldMatrix;
  47491. if (this.emitter.position) {
  47492. var emitterMesh = this.emitter;
  47493. worldMatrix = emitterMesh.getWorldMatrix();
  47494. }
  47495. else {
  47496. var emitterPosition = this.emitter;
  47497. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  47498. }
  47499. var particle;
  47500. for (var index = 0; index < newParticles; index++) {
  47501. if (this._particles.length === this._capacity) {
  47502. break;
  47503. }
  47504. if (this._stockParticles.length !== 0) {
  47505. particle = this._stockParticles.pop();
  47506. particle.age = 0;
  47507. particle.cellIndex = this.startSpriteCellID;
  47508. }
  47509. else {
  47510. particle = new BABYLON.Particle(this);
  47511. }
  47512. this._particles.push(particle);
  47513. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  47514. if (this.startPositionFunction) {
  47515. this.startPositionFunction(worldMatrix, particle.position, particle);
  47516. }
  47517. else {
  47518. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  47519. }
  47520. if (this.startDirectionFunction) {
  47521. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47522. }
  47523. else {
  47524. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47525. }
  47526. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  47527. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  47528. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  47529. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  47530. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  47531. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  47532. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  47533. }
  47534. };
  47535. ParticleSystem.prototype._getEffect = function () {
  47536. if (this._customEffect) {
  47537. return this._customEffect;
  47538. }
  47539. ;
  47540. var defines = [];
  47541. if (this._scene.clipPlane) {
  47542. defines.push("#define CLIPPLANE");
  47543. }
  47544. if (this._isAnimationSheetEnabled) {
  47545. defines.push("#define ANIMATESHEET");
  47546. }
  47547. // Effect
  47548. var join = defines.join("\n");
  47549. if (this._cachedDefines !== join) {
  47550. this._cachedDefines = join;
  47551. var attributesNamesOrOptions;
  47552. var effectCreationOption;
  47553. if (this._isAnimationSheetEnabled) {
  47554. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  47555. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  47556. }
  47557. else {
  47558. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  47559. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  47560. }
  47561. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  47562. }
  47563. return this._effect;
  47564. };
  47565. /**
  47566. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  47567. */
  47568. ParticleSystem.prototype.animate = function () {
  47569. if (!this._started)
  47570. return;
  47571. var effect = this._getEffect();
  47572. // Check
  47573. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  47574. return;
  47575. if (this._currentRenderId === this._scene.getRenderId()) {
  47576. return;
  47577. }
  47578. this._currentRenderId = this._scene.getRenderId();
  47579. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  47580. // determine the number of particles we need to create
  47581. var newParticles;
  47582. if (this.manualEmitCount > -1) {
  47583. newParticles = this.manualEmitCount;
  47584. this._newPartsExcess = 0;
  47585. this.manualEmitCount = 0;
  47586. }
  47587. else {
  47588. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  47589. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  47590. }
  47591. if (this._newPartsExcess > 1.0) {
  47592. newParticles += this._newPartsExcess >> 0;
  47593. this._newPartsExcess -= this._newPartsExcess >> 0;
  47594. }
  47595. this._alive = false;
  47596. if (!this._stopped) {
  47597. this._actualFrame += this._scaledUpdateSpeed;
  47598. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  47599. this.stop();
  47600. }
  47601. else {
  47602. newParticles = 0;
  47603. }
  47604. this._update(newParticles);
  47605. // Stopped?
  47606. if (this._stopped) {
  47607. if (!this._alive) {
  47608. this._started = false;
  47609. if (this.onAnimationEnd) {
  47610. this.onAnimationEnd();
  47611. }
  47612. if (this.disposeOnStop) {
  47613. this._scene._toBeDisposed.push(this);
  47614. }
  47615. }
  47616. }
  47617. // Animation sheet
  47618. if (this._isAnimationSheetEnabled) {
  47619. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  47620. }
  47621. else {
  47622. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  47623. }
  47624. // Update VBO
  47625. var offset = 0;
  47626. for (var index = 0; index < this._particles.length; index++) {
  47627. var particle = this._particles[index];
  47628. this._appendParticleVertexes(offset, particle);
  47629. offset += 4;
  47630. }
  47631. if (this._vertexBuffer) {
  47632. this._vertexBuffer.update(this._vertexData);
  47633. }
  47634. };
  47635. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  47636. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  47637. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  47638. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  47639. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  47640. };
  47641. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  47642. this._appendParticleVertex(offset++, particle, 0, 0);
  47643. this._appendParticleVertex(offset++, particle, 1, 0);
  47644. this._appendParticleVertex(offset++, particle, 1, 1);
  47645. this._appendParticleVertex(offset++, particle, 0, 1);
  47646. };
  47647. /**
  47648. * Rebuilds the particle system.
  47649. */
  47650. ParticleSystem.prototype.rebuild = function () {
  47651. this._createIndexBuffer();
  47652. if (this._vertexBuffer) {
  47653. this._vertexBuffer._rebuild();
  47654. }
  47655. };
  47656. /**
  47657. * Renders the particle system in its current state.
  47658. * @returns the current number of particles.
  47659. */
  47660. ParticleSystem.prototype.render = function () {
  47661. var effect = this._getEffect();
  47662. // Check
  47663. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  47664. return 0;
  47665. var engine = this._scene.getEngine();
  47666. // Render
  47667. engine.enableEffect(effect);
  47668. engine.setState(false);
  47669. var viewMatrix = this._scene.getViewMatrix();
  47670. effect.setTexture("diffuseSampler", this.particleTexture);
  47671. effect.setMatrix("view", viewMatrix);
  47672. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47673. if (this._isAnimationSheetEnabled) {
  47674. var baseSize = this.particleTexture.getBaseSize();
  47675. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  47676. }
  47677. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  47678. if (this._scene.clipPlane) {
  47679. var clipPlane = this._scene.clipPlane;
  47680. var invView = viewMatrix.clone();
  47681. invView.invert();
  47682. effect.setMatrix("invView", invView);
  47683. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  47684. }
  47685. // VBOs
  47686. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47687. // Draw order
  47688. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  47689. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  47690. }
  47691. else {
  47692. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47693. }
  47694. if (this.forceDepthWrite) {
  47695. engine.setDepthWrite(true);
  47696. }
  47697. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  47698. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47699. return this._particles.length;
  47700. };
  47701. /**
  47702. * Disposes the particle system and free the associated resources.
  47703. */
  47704. ParticleSystem.prototype.dispose = function () {
  47705. if (this._vertexBuffer) {
  47706. this._vertexBuffer.dispose();
  47707. this._vertexBuffer = null;
  47708. }
  47709. if (this._indexBuffer) {
  47710. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47711. this._indexBuffer = null;
  47712. }
  47713. if (this.particleTexture) {
  47714. this.particleTexture.dispose();
  47715. this.particleTexture = null;
  47716. }
  47717. // Remove from scene
  47718. var index = this._scene.particleSystems.indexOf(this);
  47719. if (index > -1) {
  47720. this._scene.particleSystems.splice(index, 1);
  47721. }
  47722. // Callback
  47723. this.onDisposeObservable.notifyObservers(this);
  47724. this.onDisposeObservable.clear();
  47725. };
  47726. /**
  47727. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  47728. * @param radius The radius of the sphere to emit from
  47729. * @returns the emitter
  47730. */
  47731. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  47732. if (radius === void 0) { radius = 1; }
  47733. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  47734. this.particleEmitterType = particleEmitter;
  47735. return particleEmitter;
  47736. };
  47737. /**
  47738. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  47739. * @param radius The radius of the sphere to emit from
  47740. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  47741. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  47742. * @returns the emitter
  47743. */
  47744. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  47745. if (radius === void 0) { radius = 1; }
  47746. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  47747. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  47748. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  47749. this.particleEmitterType = particleEmitter;
  47750. return particleEmitter;
  47751. };
  47752. /**
  47753. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  47754. * @param radius The radius of the cone to emit from
  47755. * @param angle The base angle of the cone
  47756. * @returns the emitter
  47757. */
  47758. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  47759. if (radius === void 0) { radius = 1; }
  47760. if (angle === void 0) { angle = Math.PI / 4; }
  47761. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  47762. this.particleEmitterType = particleEmitter;
  47763. return particleEmitter;
  47764. };
  47765. // 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.
  47766. /**
  47767. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  47768. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  47769. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  47770. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47771. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  47772. * @returns the emitter
  47773. */
  47774. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  47775. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  47776. this.direction1 = direction1;
  47777. this.direction2 = direction2;
  47778. this.minEmitBox = minEmitBox;
  47779. this.maxEmitBox = maxEmitBox;
  47780. this.particleEmitterType = particleEmitter;
  47781. return particleEmitter;
  47782. };
  47783. /**
  47784. * Clones the particle system.
  47785. * @param name The name of the cloned object
  47786. * @param newEmitter The new emitter to use
  47787. * @returns the cloned particle system
  47788. */
  47789. ParticleSystem.prototype.clone = function (name, newEmitter) {
  47790. var custom = null;
  47791. var program = null;
  47792. if (this.customShader != null) {
  47793. program = this.customShader;
  47794. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  47795. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  47796. }
  47797. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  47798. result.customShader = program;
  47799. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  47800. if (newEmitter === undefined) {
  47801. newEmitter = this.emitter;
  47802. }
  47803. result.emitter = newEmitter;
  47804. if (this.particleTexture) {
  47805. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  47806. }
  47807. if (!this.preventAutoStart) {
  47808. result.start();
  47809. }
  47810. return result;
  47811. };
  47812. /**
  47813. * Serializes the particle system to a JSON object.
  47814. * @returns the JSON object
  47815. */
  47816. ParticleSystem.prototype.serialize = function () {
  47817. var serializationObject = {};
  47818. serializationObject.name = this.name;
  47819. serializationObject.id = this.id;
  47820. // Emitter
  47821. if (this.emitter.position) {
  47822. var emitterMesh = this.emitter;
  47823. serializationObject.emitterId = emitterMesh.id;
  47824. }
  47825. else {
  47826. var emitterPosition = this.emitter;
  47827. serializationObject.emitter = emitterPosition.asArray();
  47828. }
  47829. serializationObject.capacity = this.getCapacity();
  47830. if (this.particleTexture) {
  47831. serializationObject.textureName = this.particleTexture.name;
  47832. }
  47833. // Animations
  47834. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  47835. // Particle system
  47836. serializationObject.minAngularSpeed = this.minAngularSpeed;
  47837. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  47838. serializationObject.minSize = this.minSize;
  47839. serializationObject.maxSize = this.maxSize;
  47840. serializationObject.minEmitPower = this.minEmitPower;
  47841. serializationObject.maxEmitPower = this.maxEmitPower;
  47842. serializationObject.minLifeTime = this.minLifeTime;
  47843. serializationObject.maxLifeTime = this.maxLifeTime;
  47844. serializationObject.emitRate = this.emitRate;
  47845. serializationObject.minEmitBox = this.minEmitBox.asArray();
  47846. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  47847. serializationObject.gravity = this.gravity.asArray();
  47848. serializationObject.direction1 = this.direction1.asArray();
  47849. serializationObject.direction2 = this.direction2.asArray();
  47850. serializationObject.color1 = this.color1.asArray();
  47851. serializationObject.color2 = this.color2.asArray();
  47852. serializationObject.colorDead = this.colorDead.asArray();
  47853. serializationObject.updateSpeed = this.updateSpeed;
  47854. serializationObject.targetStopDuration = this.targetStopDuration;
  47855. serializationObject.textureMask = this.textureMask.asArray();
  47856. serializationObject.blendMode = this.blendMode;
  47857. serializationObject.customShader = this.customShader;
  47858. serializationObject.preventAutoStart = this.preventAutoStart;
  47859. serializationObject.startSpriteCellID = this.startSpriteCellID;
  47860. serializationObject.endSpriteCellID = this.endSpriteCellID;
  47861. serializationObject.spriteCellLoop = this.spriteCellLoop;
  47862. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  47863. serializationObject.spriteCellWidth = this.spriteCellWidth;
  47864. serializationObject.spriteCellHeight = this.spriteCellHeight;
  47865. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  47866. return serializationObject;
  47867. };
  47868. /**
  47869. * Parses a JSON object to create a particle system.
  47870. * @param parsedParticleSystem The JSON object to parse
  47871. * @param scene The scene to create the particle system in
  47872. * @param rootUrl The root url to use to load external dependencies like texture
  47873. * @returns the Parsed particle system
  47874. */
  47875. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  47876. var name = parsedParticleSystem.name;
  47877. var custom = null;
  47878. var program = null;
  47879. if (parsedParticleSystem.customShader) {
  47880. program = parsedParticleSystem.customShader;
  47881. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  47882. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  47883. }
  47884. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  47885. particleSystem.customShader = program;
  47886. if (parsedParticleSystem.id) {
  47887. particleSystem.id = parsedParticleSystem.id;
  47888. }
  47889. // Auto start
  47890. if (parsedParticleSystem.preventAutoStart) {
  47891. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  47892. }
  47893. // Texture
  47894. if (parsedParticleSystem.textureName) {
  47895. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  47896. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  47897. }
  47898. // Emitter
  47899. if (parsedParticleSystem.emitterId) {
  47900. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  47901. }
  47902. else {
  47903. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  47904. }
  47905. // Animations
  47906. if (parsedParticleSystem.animations) {
  47907. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  47908. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  47909. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  47910. }
  47911. }
  47912. if (parsedParticleSystem.autoAnimate) {
  47913. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  47914. }
  47915. // Particle system
  47916. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  47917. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  47918. particleSystem.minSize = parsedParticleSystem.minSize;
  47919. particleSystem.maxSize = parsedParticleSystem.maxSize;
  47920. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  47921. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  47922. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  47923. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  47924. particleSystem.emitRate = parsedParticleSystem.emitRate;
  47925. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  47926. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  47927. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  47928. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  47929. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  47930. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  47931. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  47932. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  47933. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  47934. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  47935. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  47936. particleSystem.blendMode = parsedParticleSystem.blendMode;
  47937. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  47938. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  47939. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  47940. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  47941. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  47942. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  47943. if (!particleSystem.preventAutoStart) {
  47944. particleSystem.start();
  47945. }
  47946. return particleSystem;
  47947. };
  47948. /**
  47949. * Source color is added to the destination color without alpha affecting the result.
  47950. */
  47951. ParticleSystem.BLENDMODE_ONEONE = 0;
  47952. /**
  47953. * Blend current color and particle color using particle’s alpha.
  47954. */
  47955. ParticleSystem.BLENDMODE_STANDARD = 1;
  47956. return ParticleSystem;
  47957. }());
  47958. BABYLON.ParticleSystem = ParticleSystem;
  47959. })(BABYLON || (BABYLON = {}));
  47960. //# sourceMappingURL=babylon.particleSystem.js.map
  47961. var BABYLON;
  47962. (function (BABYLON) {
  47963. /**
  47964. * Particle emitter emitting particles from the inside of a box.
  47965. * It emits the particles randomly between 2 given directions.
  47966. */
  47967. var BoxParticleEmitter = /** @class */ (function () {
  47968. // to be updated like the rest of emitters when breaking changes.
  47969. // all property should be come public variables and passed through constructor.
  47970. /**
  47971. * Creates a new instance of @see BoxParticleEmitter
  47972. * @param _particleSystem the particle system associated with the emitter
  47973. */
  47974. function BoxParticleEmitter(_particleSystem) {
  47975. this._particleSystem = _particleSystem;
  47976. }
  47977. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  47978. /**
  47979. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47980. */
  47981. get: function () {
  47982. return this._particleSystem.direction1;
  47983. },
  47984. /**
  47985. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47986. */
  47987. set: function (value) {
  47988. this._particleSystem.direction1 = value;
  47989. },
  47990. enumerable: true,
  47991. configurable: true
  47992. });
  47993. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  47994. /**
  47995. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47996. */
  47997. get: function () {
  47998. return this._particleSystem.direction2;
  47999. },
  48000. /**
  48001. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48002. */
  48003. set: function (value) {
  48004. this._particleSystem.direction2 = value;
  48005. },
  48006. enumerable: true,
  48007. configurable: true
  48008. });
  48009. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  48010. /**
  48011. * 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.
  48012. */
  48013. get: function () {
  48014. return this._particleSystem.minEmitBox;
  48015. },
  48016. /**
  48017. * 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.
  48018. */
  48019. set: function (value) {
  48020. this._particleSystem.minEmitBox = value;
  48021. },
  48022. enumerable: true,
  48023. configurable: true
  48024. });
  48025. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  48026. /**
  48027. * 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.
  48028. */
  48029. get: function () {
  48030. return this._particleSystem.maxEmitBox;
  48031. },
  48032. /**
  48033. * 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.
  48034. */
  48035. set: function (value) {
  48036. this._particleSystem.maxEmitBox = value;
  48037. },
  48038. enumerable: true,
  48039. configurable: true
  48040. });
  48041. /**
  48042. * Called by the particle System when the direction is computed for the created particle.
  48043. * @param emitPower is the power of the particle (speed)
  48044. * @param worldMatrix is the world matrix of the particle system
  48045. * @param directionToUpdate is the direction vector to update with the result
  48046. * @param particle is the particle we are computed the direction for
  48047. */
  48048. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48049. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48050. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48051. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48052. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48053. };
  48054. /**
  48055. * Called by the particle System when the position is computed for the created particle.
  48056. * @param worldMatrix is the world matrix of the particle system
  48057. * @param positionToUpdate is the position vector to update with the result
  48058. * @param particle is the particle we are computed the position for
  48059. */
  48060. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48061. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  48062. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  48063. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  48064. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48065. };
  48066. return BoxParticleEmitter;
  48067. }());
  48068. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  48069. })(BABYLON || (BABYLON = {}));
  48070. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  48071. var BABYLON;
  48072. (function (BABYLON) {
  48073. /**
  48074. * Particle emitter emitting particles from the inside of a cone.
  48075. * It emits the particles alongside the cone volume from the base to the particle.
  48076. * The emission direction might be randomized.
  48077. */
  48078. var ConeParticleEmitter = /** @class */ (function () {
  48079. /**
  48080. * Creates a new instance of @see ConeParticleEmitter
  48081. * @param radius the radius of the emission cone
  48082. * @param angles the cone base angle
  48083. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48084. */
  48085. function ConeParticleEmitter(radius,
  48086. /**
  48087. * The radius of the emission cone.
  48088. */
  48089. angle,
  48090. /**
  48091. * The cone base angle.
  48092. */
  48093. directionRandomizer) {
  48094. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48095. this.angle = angle;
  48096. this.directionRandomizer = directionRandomizer;
  48097. this.radius = radius;
  48098. }
  48099. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  48100. /**
  48101. * Gets the radius of the emission cone.
  48102. */
  48103. get: function () {
  48104. return this._radius;
  48105. },
  48106. /**
  48107. * Sets the radius of the emission cone.
  48108. */
  48109. set: function (value) {
  48110. this._radius = value;
  48111. if (this.angle !== 0) {
  48112. this._height = value / Math.tan(this.angle / 2);
  48113. }
  48114. else {
  48115. this._height = 1;
  48116. }
  48117. },
  48118. enumerable: true,
  48119. configurable: true
  48120. });
  48121. /**
  48122. * Called by the particle System when the direction is computed for the created particle.
  48123. * @param emitPower is the power of the particle (speed)
  48124. * @param worldMatrix is the world matrix of the particle system
  48125. * @param directionToUpdate is the direction vector to update with the result
  48126. * @param particle is the particle we are computed the direction for
  48127. */
  48128. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48129. if (this.angle === 0) {
  48130. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  48131. }
  48132. else {
  48133. // measure the direction Vector from the emitter to the particle.
  48134. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48135. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48136. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48137. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48138. direction.x += randX;
  48139. direction.y += randY;
  48140. direction.z += randZ;
  48141. direction.normalize();
  48142. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48143. }
  48144. };
  48145. /**
  48146. * Called by the particle System when the position is computed for the created particle.
  48147. * @param worldMatrix is the world matrix of the particle system
  48148. * @param positionToUpdate is the position vector to update with the result
  48149. * @param particle is the particle we are computed the position for
  48150. */
  48151. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48152. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  48153. var h = BABYLON.Scalar.RandomRange(0, 1);
  48154. // Better distribution in a cone at normal angles.
  48155. h = 1 - h * h;
  48156. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  48157. radius = radius * h / this._height;
  48158. var randX = radius * Math.sin(s);
  48159. var randZ = radius * Math.cos(s);
  48160. var randY = h;
  48161. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48162. };
  48163. return ConeParticleEmitter;
  48164. }());
  48165. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  48166. })(BABYLON || (BABYLON = {}));
  48167. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  48168. var BABYLON;
  48169. (function (BABYLON) {
  48170. /**
  48171. * Particle emitter emitting particles from the inside of a sphere.
  48172. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  48173. */
  48174. var SphereParticleEmitter = /** @class */ (function () {
  48175. /**
  48176. * Creates a new instance of @see SphereParticleEmitter
  48177. * @param radius the radius of the emission sphere
  48178. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48179. */
  48180. function SphereParticleEmitter(
  48181. /**
  48182. * The radius of the emission sphere.
  48183. */
  48184. radius,
  48185. /**
  48186. * How much to randomize the particle direction [0-1].
  48187. */
  48188. directionRandomizer) {
  48189. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48190. this.radius = radius;
  48191. this.directionRandomizer = directionRandomizer;
  48192. }
  48193. /**
  48194. * Called by the particle System when the direction is computed for the created particle.
  48195. * @param emitPower is the power of the particle (speed)
  48196. * @param worldMatrix is the world matrix of the particle system
  48197. * @param directionToUpdate is the direction vector to update with the result
  48198. * @param particle is the particle we are computed the direction for
  48199. */
  48200. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48201. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48202. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48203. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48204. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48205. direction.x += randX;
  48206. direction.y += randY;
  48207. direction.z += randZ;
  48208. direction.normalize();
  48209. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48210. };
  48211. /**
  48212. * Called by the particle System when the position is computed for the created particle.
  48213. * @param worldMatrix is the world matrix of the particle system
  48214. * @param positionToUpdate is the position vector to update with the result
  48215. * @param particle is the particle we are computed the position for
  48216. */
  48217. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48218. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48219. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48220. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48221. var randY = this.radius * Math.cos(theta);
  48222. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48223. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48224. };
  48225. return SphereParticleEmitter;
  48226. }());
  48227. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48228. /**
  48229. * Particle emitter emitting particles from the inside of a sphere.
  48230. * It emits the particles randomly between two vectors.
  48231. */
  48232. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48233. __extends(SphereDirectedParticleEmitter, _super);
  48234. /**
  48235. * Creates a new instance of @see SphereDirectedParticleEmitter
  48236. * @param radius the radius of the emission sphere
  48237. * @param direction1 the min limit of the emission direction
  48238. * @param direction2 the max limit of the emission direction
  48239. */
  48240. function SphereDirectedParticleEmitter(radius,
  48241. /**
  48242. * The min limit of the emission direction.
  48243. */
  48244. direction1,
  48245. /**
  48246. * The max limit of the emission direction.
  48247. */
  48248. direction2) {
  48249. var _this = _super.call(this, radius) || this;
  48250. _this.direction1 = direction1;
  48251. _this.direction2 = direction2;
  48252. return _this;
  48253. }
  48254. /**
  48255. * Called by the particle System when the direction is computed for the created particle.
  48256. * @param emitPower is the power of the particle (speed)
  48257. * @param worldMatrix is the world matrix of the particle system
  48258. * @param directionToUpdate is the direction vector to update with the result
  48259. * @param particle is the particle we are computed the direction for
  48260. */
  48261. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48262. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48263. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48264. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48265. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48266. };
  48267. return SphereDirectedParticleEmitter;
  48268. }(SphereParticleEmitter));
  48269. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48270. })(BABYLON || (BABYLON = {}));
  48271. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48272. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  48273. var BABYLON;
  48274. (function (BABYLON) {
  48275. /**
  48276. * Represents one particle of a solid particle system.
  48277. * @see SolidParticleSystem
  48278. */
  48279. var SolidParticle = /** @class */ (function () {
  48280. /**
  48281. * Creates a Solid Particle object.
  48282. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48283. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48284. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48285. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  48286. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  48287. * @param shapeId (integer) is the model shape identifier in the SPS.
  48288. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48289. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  48290. */
  48291. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48292. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  48293. /**
  48294. * particle global index
  48295. */
  48296. this.idx = 0;
  48297. /**
  48298. * The color of the particle
  48299. */
  48300. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48301. /**
  48302. * The world space position of the particle.
  48303. */
  48304. this.position = BABYLON.Vector3.Zero();
  48305. /**
  48306. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  48307. */
  48308. this.rotation = BABYLON.Vector3.Zero();
  48309. /**
  48310. * The scaling of the particle.
  48311. */
  48312. this.scaling = BABYLON.Vector3.One();
  48313. /**
  48314. * The uvs of the particle.
  48315. */
  48316. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  48317. /**
  48318. * The current speed of the particle.
  48319. */
  48320. this.velocity = BABYLON.Vector3.Zero();
  48321. /**
  48322. * The pivot point in the particle local space.
  48323. */
  48324. this.pivot = BABYLON.Vector3.Zero();
  48325. /**
  48326. * Is the particle active or not ?
  48327. */
  48328. this.alive = true;
  48329. /**
  48330. * Is the particle visible or not ?
  48331. */
  48332. this.isVisible = true;
  48333. /**
  48334. * Index of this particle in the global "positions" array (Internal use)
  48335. */
  48336. this._pos = 0;
  48337. /**
  48338. * Index of this particle in the global "indices" array (Internal use)
  48339. */
  48340. this._ind = 0;
  48341. /**
  48342. * ModelShape id of this particle
  48343. */
  48344. this.shapeId = 0;
  48345. /**
  48346. * Index of the particle in its shape id (Internal use)
  48347. */
  48348. this.idxInShape = 0;
  48349. /**
  48350. * Still set as invisible in order to skip useless computations (Internal use)
  48351. */
  48352. this._stillInvisible = false;
  48353. this.idx = particleIndex;
  48354. this._pos = positionIndex;
  48355. this._ind = indiceIndex;
  48356. this._model = model;
  48357. this.shapeId = shapeId;
  48358. this.idxInShape = idxInShape;
  48359. this._sps = sps;
  48360. if (modelBoundingInfo) {
  48361. this._modelBoundingInfo = modelBoundingInfo;
  48362. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48363. }
  48364. }
  48365. Object.defineProperty(SolidParticle.prototype, "scale", {
  48366. /**
  48367. * Legacy support, changed scale to scaling
  48368. */
  48369. get: function () {
  48370. return this.scaling;
  48371. },
  48372. /**
  48373. * Legacy support, changed scale to scaling
  48374. */
  48375. set: function (scale) {
  48376. this.scaling = scale;
  48377. },
  48378. enumerable: true,
  48379. configurable: true
  48380. });
  48381. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48382. /**
  48383. * Legacy support, changed quaternion to rotationQuaternion
  48384. */
  48385. get: function () {
  48386. return this.rotationQuaternion;
  48387. },
  48388. /**
  48389. * Legacy support, changed quaternion to rotationQuaternion
  48390. */
  48391. set: function (q) {
  48392. this.rotationQuaternion = q;
  48393. },
  48394. enumerable: true,
  48395. configurable: true
  48396. });
  48397. /**
  48398. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48399. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48400. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  48401. * @returns true if it intersects
  48402. */
  48403. SolidParticle.prototype.intersectsMesh = function (target) {
  48404. if (!this._boundingInfo || !target._boundingInfo) {
  48405. return false;
  48406. }
  48407. if (this._sps._bSphereOnly) {
  48408. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48409. }
  48410. return this._boundingInfo.intersects(target._boundingInfo, false);
  48411. };
  48412. return SolidParticle;
  48413. }());
  48414. BABYLON.SolidParticle = SolidParticle;
  48415. /**
  48416. * Represents the shape of the model used by one particle of a solid particle system.
  48417. * SPS internal tool, don't use it manually.
  48418. * @see SolidParticleSystem
  48419. */
  48420. var ModelShape = /** @class */ (function () {
  48421. /**
  48422. * 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.
  48423. * SPS internal tool, don't use it manually.
  48424. * @ignore
  48425. */
  48426. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  48427. /**
  48428. * length of the shape in the model indices array (internal use)
  48429. */
  48430. this._indicesLength = 0;
  48431. this.shapeID = id;
  48432. this._shape = shape;
  48433. this._indicesLength = indicesLength;
  48434. this._shapeUV = shapeUV;
  48435. this._positionFunction = posFunction;
  48436. this._vertexFunction = vtxFunction;
  48437. }
  48438. return ModelShape;
  48439. }());
  48440. BABYLON.ModelShape = ModelShape;
  48441. /**
  48442. * Represents a Depth Sorted Particle in the solid particle system.
  48443. * @see SolidParticleSystem
  48444. */
  48445. var DepthSortedParticle = /** @class */ (function () {
  48446. function DepthSortedParticle() {
  48447. /**
  48448. * Index of the particle in the "indices" array
  48449. */
  48450. this.ind = 0;
  48451. /**
  48452. * Length of the particle shape in the "indices" array
  48453. */
  48454. this.indicesLength = 0;
  48455. /**
  48456. * Squared distance from the particle to the camera
  48457. */
  48458. this.sqDistance = 0.0;
  48459. }
  48460. return DepthSortedParticle;
  48461. }());
  48462. BABYLON.DepthSortedParticle = DepthSortedParticle;
  48463. })(BABYLON || (BABYLON = {}));
  48464. //# sourceMappingURL=babylon.solidParticle.js.map
  48465. var BABYLON;
  48466. (function (BABYLON) {
  48467. /**
  48468. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  48469. *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.
  48470. * The SPS is also a particle system. It provides some methods to manage the particles.
  48471. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  48472. *
  48473. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48474. */
  48475. var SolidParticleSystem = /** @class */ (function () {
  48476. /**
  48477. * Creates a SPS (Solid Particle System) object.
  48478. * @param name (String) is the SPS name, this will be the underlying mesh name.
  48479. * @param scene (Scene) is the scene in which the SPS is added.
  48480. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  48481. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  48482. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  48483. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  48484. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48485. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48486. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48487. */
  48488. function SolidParticleSystem(name, scene, options) {
  48489. /**
  48490. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48491. * Example : var p = SPS.particles[i];
  48492. */
  48493. this.particles = new Array();
  48494. /**
  48495. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48496. */
  48497. this.nbParticles = 0;
  48498. /**
  48499. * If the particles must ever face the camera (default false). Useful for planar particles.
  48500. */
  48501. this.billboard = false;
  48502. /**
  48503. * Recompute normals when adding a shape
  48504. */
  48505. this.recomputeNormals = true;
  48506. /**
  48507. * This a counter ofr your own usage. It's not set by any SPS functions.
  48508. */
  48509. this.counter = 0;
  48510. /**
  48511. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48512. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48513. */
  48514. this.vars = {};
  48515. /**
  48516. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  48517. */
  48518. this._bSphereOnly = false;
  48519. /**
  48520. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  48521. */
  48522. this._bSphereRadiusFactor = 1.0;
  48523. this._positions = new Array();
  48524. this._indices = new Array();
  48525. this._normals = new Array();
  48526. this._colors = new Array();
  48527. this._uvs = new Array();
  48528. this._index = 0; // indices index
  48529. this._updatable = true;
  48530. this._pickable = false;
  48531. this._isVisibilityBoxLocked = false;
  48532. this._alwaysVisible = false;
  48533. this._depthSort = false;
  48534. this._shapeCounter = 0;
  48535. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  48536. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48537. this._computeParticleColor = true;
  48538. this._computeParticleTexture = true;
  48539. this._computeParticleRotation = true;
  48540. this._computeParticleVertex = false;
  48541. this._computeBoundingBox = false;
  48542. this._depthSortParticles = true;
  48543. this._cam_axisZ = BABYLON.Vector3.Zero();
  48544. this._cam_axisY = BABYLON.Vector3.Zero();
  48545. this._cam_axisX = BABYLON.Vector3.Zero();
  48546. this._axisZ = BABYLON.Axis.Z;
  48547. this._camDir = BABYLON.Vector3.Zero();
  48548. this._camInvertedPosition = BABYLON.Vector3.Zero();
  48549. this._rotMatrix = new BABYLON.Matrix();
  48550. this._invertMatrix = new BABYLON.Matrix();
  48551. this._rotated = BABYLON.Vector3.Zero();
  48552. this._quaternion = new BABYLON.Quaternion();
  48553. this._vertex = BABYLON.Vector3.Zero();
  48554. this._normal = BABYLON.Vector3.Zero();
  48555. this._yaw = 0.0;
  48556. this._pitch = 0.0;
  48557. this._roll = 0.0;
  48558. this._halfroll = 0.0;
  48559. this._halfpitch = 0.0;
  48560. this._halfyaw = 0.0;
  48561. this._sinRoll = 0.0;
  48562. this._cosRoll = 0.0;
  48563. this._sinPitch = 0.0;
  48564. this._cosPitch = 0.0;
  48565. this._sinYaw = 0.0;
  48566. this._cosYaw = 0.0;
  48567. this._mustUnrotateFixedNormals = false;
  48568. this._minimum = BABYLON.Tmp.Vector3[0];
  48569. this._maximum = BABYLON.Tmp.Vector3[1];
  48570. this._minBbox = BABYLON.Tmp.Vector3[4];
  48571. this._maxBbox = BABYLON.Tmp.Vector3[5];
  48572. this._particlesIntersect = false;
  48573. this._depthSortFunction = function (p1, p2) {
  48574. return (p2.sqDistance - p1.sqDistance);
  48575. };
  48576. this._needs32Bits = false;
  48577. this.name = name;
  48578. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48579. this._camera = scene.activeCamera;
  48580. this._pickable = options ? options.isPickable : false;
  48581. this._depthSort = options ? options.enableDepthSort : false;
  48582. this._particlesIntersect = options ? options.particleIntersection : false;
  48583. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  48584. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  48585. if (options && options.updatable) {
  48586. this._updatable = options.updatable;
  48587. }
  48588. else {
  48589. this._updatable = true;
  48590. }
  48591. if (this._pickable) {
  48592. this.pickedParticles = [];
  48593. }
  48594. if (this._depthSort) {
  48595. this.depthSortedParticles = [];
  48596. }
  48597. }
  48598. /**
  48599. * Builds the SPS underlying mesh. Returns a standard Mesh.
  48600. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  48601. * @returns the created mesh
  48602. */
  48603. SolidParticleSystem.prototype.buildMesh = function () {
  48604. if (this.nbParticles === 0) {
  48605. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  48606. this.addShape(triangle, 1);
  48607. triangle.dispose();
  48608. }
  48609. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  48610. this._positions32 = new Float32Array(this._positions);
  48611. this._uvs32 = new Float32Array(this._uvs);
  48612. this._colors32 = new Float32Array(this._colors);
  48613. if (this.recomputeNormals) {
  48614. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  48615. }
  48616. this._normals32 = new Float32Array(this._normals);
  48617. this._fixedNormal32 = new Float32Array(this._normals);
  48618. if (this._mustUnrotateFixedNormals) {
  48619. this._unrotateFixedNormals();
  48620. }
  48621. var vertexData = new BABYLON.VertexData();
  48622. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  48623. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  48624. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  48625. if (this._uvs32) {
  48626. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  48627. ;
  48628. }
  48629. if (this._colors32) {
  48630. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  48631. }
  48632. var mesh = new BABYLON.Mesh(this.name, this._scene);
  48633. vertexData.applyToMesh(mesh, this._updatable);
  48634. this.mesh = mesh;
  48635. this.mesh.isPickable = this._pickable;
  48636. // free memory
  48637. if (!this._depthSort) {
  48638. this._indices = null;
  48639. }
  48640. this._positions = null;
  48641. this._normals = null;
  48642. this._uvs = null;
  48643. this._colors = null;
  48644. if (!this._updatable) {
  48645. this.particles.length = 0;
  48646. }
  48647. return mesh;
  48648. };
  48649. /**
  48650. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  48651. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  48652. * Thus the particles generated from `digest()` have their property `position` set yet.
  48653. * @param mesh ( Mesh ) is the mesh to be digested
  48654. * @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
  48655. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  48656. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  48657. * @returns the current SPS
  48658. */
  48659. SolidParticleSystem.prototype.digest = function (mesh, options) {
  48660. var size = (options && options.facetNb) || 1;
  48661. var number = (options && options.number) || 0;
  48662. var delta = (options && options.delta) || 0;
  48663. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48664. var meshInd = mesh.getIndices();
  48665. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48666. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48667. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48668. var f = 0; // facet counter
  48669. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  48670. // compute size from number
  48671. if (number) {
  48672. number = (number > totalFacets) ? totalFacets : number;
  48673. size = Math.round(totalFacets / number);
  48674. delta = 0;
  48675. }
  48676. else {
  48677. size = (size > totalFacets) ? totalFacets : size;
  48678. }
  48679. var facetPos = []; // submesh positions
  48680. var facetInd = []; // submesh indices
  48681. var facetUV = []; // submesh UV
  48682. var facetCol = []; // submesh colors
  48683. var barycenter = BABYLON.Tmp.Vector3[0];
  48684. var sizeO = size;
  48685. while (f < totalFacets) {
  48686. size = sizeO + Math.floor((1 + delta) * Math.random());
  48687. if (f > totalFacets - size) {
  48688. size = totalFacets - f;
  48689. }
  48690. // reset temp arrays
  48691. facetPos.length = 0;
  48692. facetInd.length = 0;
  48693. facetUV.length = 0;
  48694. facetCol.length = 0;
  48695. // iterate over "size" facets
  48696. var fi = 0;
  48697. for (var j = f * 3; j < (f + size) * 3; j++) {
  48698. facetInd.push(fi);
  48699. var i = meshInd[j];
  48700. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  48701. if (meshUV) {
  48702. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  48703. }
  48704. if (meshCol) {
  48705. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  48706. }
  48707. fi++;
  48708. }
  48709. // create a model shape for each single particle
  48710. var idx = this.nbParticles;
  48711. var shape = this._posToShape(facetPos);
  48712. var shapeUV = this._uvsToShapeUV(facetUV);
  48713. // compute the barycenter of the shape
  48714. var v;
  48715. for (v = 0; v < shape.length; v++) {
  48716. barycenter.addInPlace(shape[v]);
  48717. }
  48718. barycenter.scaleInPlace(1 / shape.length);
  48719. // shift the shape from its barycenter to the origin
  48720. for (v = 0; v < shape.length; v++) {
  48721. shape[v].subtractInPlace(barycenter);
  48722. }
  48723. var bInfo;
  48724. if (this._particlesIntersect) {
  48725. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  48726. }
  48727. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  48728. // add the particle in the SPS
  48729. var currentPos = this._positions.length;
  48730. var currentInd = this._indices.length;
  48731. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  48732. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  48733. // initialize the particle position
  48734. this.particles[this.nbParticles].position.addInPlace(barycenter);
  48735. this._index += shape.length;
  48736. idx++;
  48737. this.nbParticles++;
  48738. this._shapeCounter++;
  48739. f += size;
  48740. }
  48741. return this;
  48742. };
  48743. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  48744. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  48745. var index = 0;
  48746. var idx = 0;
  48747. for (var p = 0; p < this.particles.length; p++) {
  48748. this._particle = this.particles[p];
  48749. this._shape = this._particle._model._shape;
  48750. if (this._particle.rotationQuaternion) {
  48751. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48752. }
  48753. else {
  48754. this._yaw = this._particle.rotation.y;
  48755. this._pitch = this._particle.rotation.x;
  48756. this._roll = this._particle.rotation.z;
  48757. this._quaternionRotationYPR();
  48758. }
  48759. this._quaternionToRotationMatrix();
  48760. this._rotMatrix.invertToRef(this._invertMatrix);
  48761. for (var pt = 0; pt < this._shape.length; pt++) {
  48762. idx = index + pt * 3;
  48763. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  48764. this._fixedNormal32[idx] = this._normal.x;
  48765. this._fixedNormal32[idx + 1] = this._normal.y;
  48766. this._fixedNormal32[idx + 2] = this._normal.z;
  48767. }
  48768. index = idx + 3;
  48769. }
  48770. };
  48771. //reset copy
  48772. SolidParticleSystem.prototype._resetCopy = function () {
  48773. this._copy.position.x = 0;
  48774. this._copy.position.y = 0;
  48775. this._copy.position.z = 0;
  48776. this._copy.rotation.x = 0;
  48777. this._copy.rotation.y = 0;
  48778. this._copy.rotation.z = 0;
  48779. this._copy.rotationQuaternion = null;
  48780. this._copy.scaling.x = 1.0;
  48781. this._copy.scaling.y = 1.0;
  48782. this._copy.scaling.z = 1.0;
  48783. this._copy.uvs.x = 0;
  48784. this._copy.uvs.y = 0;
  48785. this._copy.uvs.z = 1.0;
  48786. this._copy.uvs.w = 1.0;
  48787. this._copy.color = null;
  48788. };
  48789. // _meshBuilder : inserts the shape model in the global SPS mesh
  48790. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  48791. var i;
  48792. var u = 0;
  48793. var c = 0;
  48794. var n = 0;
  48795. this._resetCopy();
  48796. if (options && options.positionFunction) {
  48797. options.positionFunction(this._copy, idx, idxInShape);
  48798. this._mustUnrotateFixedNormals = true;
  48799. }
  48800. if (this._copy.rotationQuaternion) {
  48801. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48802. }
  48803. else {
  48804. this._yaw = this._copy.rotation.y;
  48805. this._pitch = this._copy.rotation.x;
  48806. this._roll = this._copy.rotation.z;
  48807. this._quaternionRotationYPR();
  48808. }
  48809. this._quaternionToRotationMatrix();
  48810. for (i = 0; i < shape.length; i++) {
  48811. this._vertex.x = shape[i].x;
  48812. this._vertex.y = shape[i].y;
  48813. this._vertex.z = shape[i].z;
  48814. if (options && options.vertexFunction) {
  48815. options.vertexFunction(this._copy, this._vertex, i);
  48816. }
  48817. this._vertex.x *= this._copy.scaling.x;
  48818. this._vertex.y *= this._copy.scaling.y;
  48819. this._vertex.z *= this._copy.scaling.z;
  48820. this._vertex.x += this._copy.pivot.x;
  48821. this._vertex.y += this._copy.pivot.y;
  48822. this._vertex.z += this._copy.pivot.z;
  48823. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48824. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  48825. if (meshUV) {
  48826. 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);
  48827. u += 2;
  48828. }
  48829. if (this._copy.color) {
  48830. this._color = this._copy.color;
  48831. }
  48832. else if (meshCol && meshCol[c] !== undefined) {
  48833. this._color.r = meshCol[c];
  48834. this._color.g = meshCol[c + 1];
  48835. this._color.b = meshCol[c + 2];
  48836. this._color.a = meshCol[c + 3];
  48837. }
  48838. else {
  48839. this._color.r = 1.0;
  48840. this._color.g = 1.0;
  48841. this._color.b = 1.0;
  48842. this._color.a = 1.0;
  48843. }
  48844. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  48845. c += 4;
  48846. if (!this.recomputeNormals && meshNor) {
  48847. this._normal.x = meshNor[n];
  48848. this._normal.y = meshNor[n + 1];
  48849. this._normal.z = meshNor[n + 2];
  48850. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  48851. normals.push(this._normal.x, this._normal.y, this._normal.z);
  48852. n += 3;
  48853. }
  48854. }
  48855. for (i = 0; i < meshInd.length; i++) {
  48856. var current_ind = p + meshInd[i];
  48857. indices.push(current_ind);
  48858. if (current_ind > 65535) {
  48859. this._needs32Bits = true;
  48860. }
  48861. }
  48862. if (this._pickable) {
  48863. var nbfaces = meshInd.length / 3;
  48864. for (i = 0; i < nbfaces; i++) {
  48865. this.pickedParticles.push({ idx: idx, faceId: i });
  48866. }
  48867. }
  48868. if (this._depthSort) {
  48869. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  48870. }
  48871. return this._copy;
  48872. };
  48873. // returns a shape array from positions array
  48874. SolidParticleSystem.prototype._posToShape = function (positions) {
  48875. var shape = [];
  48876. for (var i = 0; i < positions.length; i += 3) {
  48877. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  48878. }
  48879. return shape;
  48880. };
  48881. // returns a shapeUV array from a Vector4 uvs
  48882. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  48883. var shapeUV = [];
  48884. if (uvs) {
  48885. for (var i = 0; i < uvs.length; i++)
  48886. shapeUV.push(uvs[i]);
  48887. }
  48888. return shapeUV;
  48889. };
  48890. // adds a new particle object in the particles array
  48891. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  48892. if (bInfo === void 0) { bInfo = null; }
  48893. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  48894. this.particles.push(sp);
  48895. return sp;
  48896. };
  48897. /**
  48898. * Adds some particles to the SPS from the model shape. Returns the shape id.
  48899. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  48900. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  48901. * @param nb (positive integer) the number of particles to be created from this model
  48902. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  48903. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  48904. * @returns the number of shapes in the system
  48905. */
  48906. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  48907. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48908. var meshInd = mesh.getIndices();
  48909. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48910. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48911. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48912. var bbInfo;
  48913. if (this._particlesIntersect) {
  48914. bbInfo = mesh.getBoundingInfo();
  48915. }
  48916. var shape = this._posToShape(meshPos);
  48917. var shapeUV = this._uvsToShapeUV(meshUV);
  48918. var posfunc = options ? options.positionFunction : null;
  48919. var vtxfunc = options ? options.vertexFunction : null;
  48920. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  48921. // particles
  48922. var sp;
  48923. var currentCopy;
  48924. var idx = this.nbParticles;
  48925. for (var i = 0; i < nb; i++) {
  48926. var currentPos = this._positions.length;
  48927. var currentInd = this._indices.length;
  48928. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  48929. if (this._updatable) {
  48930. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  48931. sp.position.copyFrom(currentCopy.position);
  48932. sp.rotation.copyFrom(currentCopy.rotation);
  48933. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  48934. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  48935. }
  48936. if (currentCopy.color && sp.color) {
  48937. sp.color.copyFrom(currentCopy.color);
  48938. }
  48939. sp.scaling.copyFrom(currentCopy.scaling);
  48940. sp.uvs.copyFrom(currentCopy.uvs);
  48941. }
  48942. this._index += shape.length;
  48943. idx++;
  48944. }
  48945. this.nbParticles += nb;
  48946. this._shapeCounter++;
  48947. return this._shapeCounter - 1;
  48948. };
  48949. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  48950. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  48951. this._resetCopy();
  48952. if (particle._model._positionFunction) {
  48953. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  48954. }
  48955. if (this._copy.rotationQuaternion) {
  48956. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  48957. }
  48958. else {
  48959. this._yaw = this._copy.rotation.y;
  48960. this._pitch = this._copy.rotation.x;
  48961. this._roll = this._copy.rotation.z;
  48962. this._quaternionRotationYPR();
  48963. }
  48964. this._quaternionToRotationMatrix();
  48965. this._shape = particle._model._shape;
  48966. for (var pt = 0; pt < this._shape.length; pt++) {
  48967. this._vertex.x = this._shape[pt].x;
  48968. this._vertex.y = this._shape[pt].y;
  48969. this._vertex.z = this._shape[pt].z;
  48970. if (particle._model._vertexFunction) {
  48971. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  48972. }
  48973. this._vertex.x *= this._copy.scaling.x;
  48974. this._vertex.y *= this._copy.scaling.y;
  48975. this._vertex.z *= this._copy.scaling.z;
  48976. this._vertex.x += this._copy.pivot.x;
  48977. this._vertex.y += this._copy.pivot.y;
  48978. this._vertex.z += this._copy.pivot.z;
  48979. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  48980. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  48981. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  48982. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  48983. }
  48984. particle.position.x = 0.0;
  48985. particle.position.y = 0.0;
  48986. particle.position.z = 0.0;
  48987. particle.rotation.x = 0.0;
  48988. particle.rotation.y = 0.0;
  48989. particle.rotation.z = 0.0;
  48990. particle.rotationQuaternion = null;
  48991. particle.scaling.x = 1.0;
  48992. particle.scaling.y = 1.0;
  48993. particle.scaling.z = 1.0;
  48994. };
  48995. /**
  48996. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  48997. * @returns the SPS.
  48998. */
  48999. SolidParticleSystem.prototype.rebuildMesh = function () {
  49000. for (var p = 0; p < this.particles.length; p++) {
  49001. this._rebuildParticle(this.particles[p]);
  49002. }
  49003. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49004. return this;
  49005. };
  49006. /**
  49007. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49008. * This method calls `updateParticle()` for each particle of the SPS.
  49009. * For an animated SPS, it is usually called within the render loop.
  49010. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49011. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49012. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49013. * @returns the SPS.
  49014. */
  49015. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49016. if (start === void 0) { start = 0; }
  49017. if (end === void 0) { end = this.nbParticles - 1; }
  49018. if (update === void 0) { update = true; }
  49019. if (!this._updatable) {
  49020. return this;
  49021. }
  49022. // custom beforeUpdate
  49023. this.beforeUpdateParticles(start, end, update);
  49024. this._cam_axisX.x = 1.0;
  49025. this._cam_axisX.y = 0.0;
  49026. this._cam_axisX.z = 0.0;
  49027. this._cam_axisY.x = 0.0;
  49028. this._cam_axisY.y = 1.0;
  49029. this._cam_axisY.z = 0.0;
  49030. this._cam_axisZ.x = 0.0;
  49031. this._cam_axisZ.y = 0.0;
  49032. this._cam_axisZ.z = 1.0;
  49033. // cases when the World Matrix is to be computed first
  49034. if (this.billboard || this._depthSort) {
  49035. this.mesh.computeWorldMatrix(true);
  49036. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49037. }
  49038. // if the particles will always face the camera
  49039. if (this.billboard) {
  49040. // compute the camera position and un-rotate it by the current mesh rotation
  49041. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49042. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49043. this._cam_axisZ.normalize();
  49044. // same for camera up vector extracted from the cam view matrix
  49045. var view = this._camera.getViewMatrix(true);
  49046. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49047. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49048. this._cam_axisY.normalize();
  49049. this._cam_axisX.normalize();
  49050. }
  49051. // if depthSort, compute the camera global position in the mesh local system
  49052. if (this._depthSort) {
  49053. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49054. }
  49055. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49056. var idx = 0; // current position index in the global array positions32
  49057. var index = 0; // position start index in the global array positions32 of the current particle
  49058. var colidx = 0; // current color index in the global array colors32
  49059. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49060. var uvidx = 0; // current uv index in the global array uvs32
  49061. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49062. var pt = 0; // current index in the particle model shape
  49063. if (this.mesh.isFacetDataEnabled) {
  49064. this._computeBoundingBox = true;
  49065. }
  49066. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49067. if (this._computeBoundingBox) {
  49068. if (start == 0 && end == this.nbParticles - 1) {
  49069. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49070. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49071. }
  49072. else {
  49073. if (this.mesh._boundingInfo) {
  49074. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49075. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49076. }
  49077. }
  49078. }
  49079. // particle loop
  49080. index = this.particles[start]._pos;
  49081. var vpos = (index / 3) | 0;
  49082. colorIndex = vpos * 4;
  49083. uvIndex = vpos * 2;
  49084. for (var p = start; p <= end; p++) {
  49085. this._particle = this.particles[p];
  49086. this._shape = this._particle._model._shape;
  49087. this._shapeUV = this._particle._model._shapeUV;
  49088. // call to custom user function to update the particle properties
  49089. this.updateParticle(this._particle);
  49090. // camera-particle distance for depth sorting
  49091. if (this._depthSort && this._depthSortParticles) {
  49092. var dsp = this.depthSortedParticles[p];
  49093. dsp.ind = this._particle._ind;
  49094. dsp.indicesLength = this._particle._model._indicesLength;
  49095. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49096. }
  49097. // skip the computations for inactive or already invisible particles
  49098. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49099. // increment indexes for the next particle
  49100. pt = this._shape.length;
  49101. index += pt * 3;
  49102. colorIndex += pt * 4;
  49103. uvIndex += pt * 2;
  49104. continue;
  49105. }
  49106. if (this._particle.isVisible) {
  49107. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49108. // particle rotation matrix
  49109. if (this.billboard) {
  49110. this._particle.rotation.x = 0.0;
  49111. this._particle.rotation.y = 0.0;
  49112. }
  49113. if (this._computeParticleRotation || this.billboard) {
  49114. if (this._particle.rotationQuaternion) {
  49115. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49116. }
  49117. else {
  49118. this._yaw = this._particle.rotation.y;
  49119. this._pitch = this._particle.rotation.x;
  49120. this._roll = this._particle.rotation.z;
  49121. this._quaternionRotationYPR();
  49122. }
  49123. this._quaternionToRotationMatrix();
  49124. }
  49125. // particle vertex loop
  49126. for (pt = 0; pt < this._shape.length; pt++) {
  49127. idx = index + pt * 3;
  49128. colidx = colorIndex + pt * 4;
  49129. uvidx = uvIndex + pt * 2;
  49130. this._vertex.x = this._shape[pt].x;
  49131. this._vertex.y = this._shape[pt].y;
  49132. this._vertex.z = this._shape[pt].z;
  49133. if (this._computeParticleVertex) {
  49134. this.updateParticleVertex(this._particle, this._vertex, pt);
  49135. }
  49136. // positions
  49137. this._vertex.x *= this._particle.scaling.x;
  49138. this._vertex.y *= this._particle.scaling.y;
  49139. this._vertex.z *= this._particle.scaling.z;
  49140. this._vertex.x += this._particle.pivot.x;
  49141. this._vertex.y += this._particle.pivot.y;
  49142. this._vertex.z += this._particle.pivot.z;
  49143. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49144. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49145. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49146. 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;
  49147. 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;
  49148. 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;
  49149. if (this._computeBoundingBox) {
  49150. if (this._positions32[idx] < this._minimum.x) {
  49151. this._minimum.x = this._positions32[idx];
  49152. }
  49153. if (this._positions32[idx] > this._maximum.x) {
  49154. this._maximum.x = this._positions32[idx];
  49155. }
  49156. if (this._positions32[idx + 1] < this._minimum.y) {
  49157. this._minimum.y = this._positions32[idx + 1];
  49158. }
  49159. if (this._positions32[idx + 1] > this._maximum.y) {
  49160. this._maximum.y = this._positions32[idx + 1];
  49161. }
  49162. if (this._positions32[idx + 2] < this._minimum.z) {
  49163. this._minimum.z = this._positions32[idx + 2];
  49164. }
  49165. if (this._positions32[idx + 2] > this._maximum.z) {
  49166. this._maximum.z = this._positions32[idx + 2];
  49167. }
  49168. }
  49169. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49170. if (!this._computeParticleVertex) {
  49171. this._normal.x = this._fixedNormal32[idx];
  49172. this._normal.y = this._fixedNormal32[idx + 1];
  49173. this._normal.z = this._fixedNormal32[idx + 2];
  49174. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49175. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49176. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49177. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49178. 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;
  49179. 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;
  49180. }
  49181. if (this._computeParticleColor && this._particle.color) {
  49182. this._colors32[colidx] = this._particle.color.r;
  49183. this._colors32[colidx + 1] = this._particle.color.g;
  49184. this._colors32[colidx + 2] = this._particle.color.b;
  49185. this._colors32[colidx + 3] = this._particle.color.a;
  49186. }
  49187. if (this._computeParticleTexture) {
  49188. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49189. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49190. }
  49191. }
  49192. }
  49193. else {
  49194. this._particle._stillInvisible = true; // mark the particle as invisible
  49195. for (pt = 0; pt < this._shape.length; pt++) {
  49196. idx = index + pt * 3;
  49197. colidx = colorIndex + pt * 4;
  49198. uvidx = uvIndex + pt * 2;
  49199. this._positions32[idx] = 0.0;
  49200. this._positions32[idx + 1] = 0.0;
  49201. this._positions32[idx + 2] = 0.0;
  49202. this._normals32[idx] = 0.0;
  49203. this._normals32[idx + 1] = 0.0;
  49204. this._normals32[idx + 2] = 0.0;
  49205. if (this._computeParticleColor && this._particle.color) {
  49206. this._colors32[colidx] = this._particle.color.r;
  49207. this._colors32[colidx + 1] = this._particle.color.g;
  49208. this._colors32[colidx + 2] = this._particle.color.b;
  49209. this._colors32[colidx + 3] = this._particle.color.a;
  49210. }
  49211. if (this._computeParticleTexture) {
  49212. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49213. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49214. }
  49215. }
  49216. }
  49217. // if the particle intersections must be computed : update the bbInfo
  49218. if (this._particlesIntersect) {
  49219. var bInfo = this._particle._boundingInfo;
  49220. var bBox = bInfo.boundingBox;
  49221. var bSphere = bInfo.boundingSphere;
  49222. if (!this._bSphereOnly) {
  49223. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49224. for (var b = 0; b < bBox.vectors.length; b++) {
  49225. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49226. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49227. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49228. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49229. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49230. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49231. 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;
  49232. 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;
  49233. 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;
  49234. }
  49235. bBox._update(this.mesh._worldMatrix);
  49236. }
  49237. // place and scale the particle bouding sphere in the SPS local system, then update it
  49238. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49239. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49240. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49241. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49242. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49243. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49244. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49245. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49246. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49247. 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));
  49248. bSphere._update(this.mesh._worldMatrix);
  49249. }
  49250. // increment indexes for the next particle
  49251. index = idx + 3;
  49252. colorIndex = colidx + 4;
  49253. uvIndex = uvidx + 2;
  49254. }
  49255. // if the VBO must be updated
  49256. if (update) {
  49257. if (this._computeParticleColor) {
  49258. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49259. }
  49260. if (this._computeParticleTexture) {
  49261. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49262. }
  49263. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49264. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  49265. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  49266. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49267. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  49268. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  49269. for (var i = 0; i < this._normals32.length; i++) {
  49270. this._fixedNormal32[i] = this._normals32[i];
  49271. }
  49272. }
  49273. if (!this.mesh.areNormalsFrozen) {
  49274. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49275. }
  49276. }
  49277. if (this._depthSort && this._depthSortParticles) {
  49278. this.depthSortedParticles.sort(this._depthSortFunction);
  49279. var dspl = this.depthSortedParticles.length;
  49280. var sorted = 0;
  49281. var lind = 0;
  49282. var sind = 0;
  49283. var sid = 0;
  49284. for (sorted = 0; sorted < dspl; sorted++) {
  49285. lind = this.depthSortedParticles[sorted].indicesLength;
  49286. sind = this.depthSortedParticles[sorted].ind;
  49287. for (var i = 0; i < lind; i++) {
  49288. this._indices32[sid] = this._indices[sind + i];
  49289. sid++;
  49290. }
  49291. }
  49292. this.mesh.updateIndices(this._indices32);
  49293. }
  49294. }
  49295. if (this._computeBoundingBox) {
  49296. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49297. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49298. }
  49299. this.afterUpdateParticles(start, end, update);
  49300. return this;
  49301. };
  49302. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49303. this._halfroll = this._roll * 0.5;
  49304. this._halfpitch = this._pitch * 0.5;
  49305. this._halfyaw = this._yaw * 0.5;
  49306. this._sinRoll = Math.sin(this._halfroll);
  49307. this._cosRoll = Math.cos(this._halfroll);
  49308. this._sinPitch = Math.sin(this._halfpitch);
  49309. this._cosPitch = Math.cos(this._halfpitch);
  49310. this._sinYaw = Math.sin(this._halfyaw);
  49311. this._cosYaw = Math.cos(this._halfyaw);
  49312. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  49313. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  49314. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  49315. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  49316. };
  49317. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49318. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49319. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49320. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49321. this._rotMatrix.m[3] = 0;
  49322. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49323. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49324. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49325. this._rotMatrix.m[7] = 0;
  49326. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49327. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49328. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49329. this._rotMatrix.m[11] = 0;
  49330. this._rotMatrix.m[12] = 0;
  49331. this._rotMatrix.m[13] = 0;
  49332. this._rotMatrix.m[14] = 0;
  49333. this._rotMatrix.m[15] = 1.0;
  49334. };
  49335. /**
  49336. * Disposes the SPS.
  49337. */
  49338. SolidParticleSystem.prototype.dispose = function () {
  49339. this.mesh.dispose();
  49340. this.vars = null;
  49341. // drop references to internal big arrays for the GC
  49342. this._positions = null;
  49343. this._indices = null;
  49344. this._normals = null;
  49345. this._uvs = null;
  49346. this._colors = null;
  49347. this._indices32 = null;
  49348. this._positions32 = null;
  49349. this._normals32 = null;
  49350. this._fixedNormal32 = null;
  49351. this._uvs32 = null;
  49352. this._colors32 = null;
  49353. this.pickedParticles = null;
  49354. };
  49355. /**
  49356. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49357. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49358. * @returns the SPS.
  49359. */
  49360. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49361. if (!this._isVisibilityBoxLocked) {
  49362. this.mesh.refreshBoundingInfo();
  49363. }
  49364. return this;
  49365. };
  49366. /**
  49367. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49368. * @param size the size (float) of the visibility box
  49369. * note : this doesn't lock the SPS mesh bounding box.
  49370. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49371. */
  49372. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49373. var vis = size / 2;
  49374. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49375. };
  49376. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49377. /**
  49378. * Gets whether the SPS as always visible or not
  49379. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49380. */
  49381. get: function () {
  49382. return this._alwaysVisible;
  49383. },
  49384. /**
  49385. * Sets the SPS as always visible or not
  49386. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49387. */
  49388. set: function (val) {
  49389. this._alwaysVisible = val;
  49390. this.mesh.alwaysSelectAsActiveMesh = val;
  49391. },
  49392. enumerable: true,
  49393. configurable: true
  49394. });
  49395. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49396. /**
  49397. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49398. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49399. */
  49400. get: function () {
  49401. return this._isVisibilityBoxLocked;
  49402. },
  49403. /**
  49404. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49405. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49406. */
  49407. set: function (val) {
  49408. this._isVisibilityBoxLocked = val;
  49409. var boundingInfo = this.mesh.getBoundingInfo();
  49410. boundingInfo.isLocked = val;
  49411. },
  49412. enumerable: true,
  49413. configurable: true
  49414. });
  49415. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49416. /**
  49417. * Gets if `setParticles()` computes the particle rotations or not.
  49418. * Default value : true. The SPS is faster when it's set to false.
  49419. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49420. */
  49421. get: function () {
  49422. return this._computeParticleRotation;
  49423. },
  49424. /**
  49425. * Tells to `setParticles()` to compute the particle rotations or not.
  49426. * Default value : true. The SPS is faster when it's set to false.
  49427. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49428. */
  49429. set: function (val) {
  49430. this._computeParticleRotation = val;
  49431. },
  49432. enumerable: true,
  49433. configurable: true
  49434. });
  49435. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49436. /**
  49437. * Gets if `setParticles()` computes the particle colors or not.
  49438. * Default value : true. The SPS is faster when it's set to false.
  49439. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49440. */
  49441. get: function () {
  49442. return this._computeParticleColor;
  49443. },
  49444. /**
  49445. * Tells to `setParticles()` to compute the particle colors or not.
  49446. * Default value : true. The SPS is faster when it's set to false.
  49447. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49448. */
  49449. set: function (val) {
  49450. this._computeParticleColor = val;
  49451. },
  49452. enumerable: true,
  49453. configurable: true
  49454. });
  49455. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49456. /**
  49457. * Gets if `setParticles()` computes the particle textures or not.
  49458. * Default value : true. The SPS is faster when it's set to false.
  49459. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49460. */
  49461. get: function () {
  49462. return this._computeParticleTexture;
  49463. },
  49464. set: function (val) {
  49465. this._computeParticleTexture = val;
  49466. },
  49467. enumerable: true,
  49468. configurable: true
  49469. });
  49470. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49471. /**
  49472. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  49473. * Default value : false. The SPS is faster when it's set to false.
  49474. * Note : the particle custom vertex positions aren't stored values.
  49475. */
  49476. get: function () {
  49477. return this._computeParticleVertex;
  49478. },
  49479. /**
  49480. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49481. * Default value : false. The SPS is faster when it's set to false.
  49482. * Note : the particle custom vertex positions aren't stored values.
  49483. */
  49484. set: function (val) {
  49485. this._computeParticleVertex = val;
  49486. },
  49487. enumerable: true,
  49488. configurable: true
  49489. });
  49490. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49491. /**
  49492. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  49493. */
  49494. get: function () {
  49495. return this._computeBoundingBox;
  49496. },
  49497. /**
  49498. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49499. */
  49500. set: function (val) {
  49501. this._computeBoundingBox = val;
  49502. },
  49503. enumerable: true,
  49504. configurable: true
  49505. });
  49506. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  49507. /**
  49508. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  49509. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49510. * Default : `true`
  49511. */
  49512. get: function () {
  49513. return this._depthSortParticles;
  49514. },
  49515. /**
  49516. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  49517. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49518. * Default : `true`
  49519. */
  49520. set: function (val) {
  49521. this._depthSortParticles = val;
  49522. },
  49523. enumerable: true,
  49524. configurable: true
  49525. });
  49526. // =======================================================================
  49527. // Particle behavior logic
  49528. // these following methods may be overwritten by the user to fit his needs
  49529. /**
  49530. * This function does nothing. It may be overwritten to set all the particle first values.
  49531. * The SPS doesn't call this function, you may have to call it by your own.
  49532. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49533. */
  49534. SolidParticleSystem.prototype.initParticles = function () {
  49535. };
  49536. /**
  49537. * This function does nothing. It may be overwritten to recycle a particle.
  49538. * The SPS doesn't call this function, you may have to call it by your own.
  49539. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49540. * @param particle The particle to recycle
  49541. * @returns the recycled particle
  49542. */
  49543. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49544. return particle;
  49545. };
  49546. /**
  49547. * Updates a particle : this function should be overwritten by the user.
  49548. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49549. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49550. * @example : just set a particle position or velocity and recycle conditions
  49551. * @param particle The particle to update
  49552. * @returns the updated particle
  49553. */
  49554. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49555. return particle;
  49556. };
  49557. /**
  49558. * Updates a vertex of a particle : it can be overwritten by the user.
  49559. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49560. * @param particle the current particle
  49561. * @param vertex the current index of the current particle
  49562. * @param pt the index of the current vertex in the particle shape
  49563. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49564. * @example : just set a vertex particle position
  49565. * @returns the updated vertex
  49566. */
  49567. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  49568. return vertex;
  49569. };
  49570. /**
  49571. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  49572. * This does nothing and may be overwritten by the user.
  49573. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49574. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49575. * @param update the boolean update value actually passed to setParticles()
  49576. */
  49577. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  49578. };
  49579. /**
  49580. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  49581. * This will be passed three parameters.
  49582. * This does nothing and may be overwritten by the user.
  49583. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49584. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  49585. * @param update the boolean update value actually passed to setParticles()
  49586. */
  49587. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  49588. };
  49589. return SolidParticleSystem;
  49590. }());
  49591. BABYLON.SolidParticleSystem = SolidParticleSystem;
  49592. })(BABYLON || (BABYLON = {}));
  49593. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  49594. var BABYLON;
  49595. (function (BABYLON) {
  49596. var ShaderMaterial = /** @class */ (function (_super) {
  49597. __extends(ShaderMaterial, _super);
  49598. function ShaderMaterial(name, scene, shaderPath, options) {
  49599. var _this = _super.call(this, name, scene) || this;
  49600. _this._textures = {};
  49601. _this._textureArrays = {};
  49602. _this._floats = {};
  49603. _this._ints = {};
  49604. _this._floatsArrays = {};
  49605. _this._colors3 = {};
  49606. _this._colors3Arrays = {};
  49607. _this._colors4 = {};
  49608. _this._vectors2 = {};
  49609. _this._vectors3 = {};
  49610. _this._vectors4 = {};
  49611. _this._matrices = {};
  49612. _this._matrices3x3 = {};
  49613. _this._matrices2x2 = {};
  49614. _this._vectors2Arrays = {};
  49615. _this._vectors3Arrays = {};
  49616. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  49617. _this._shaderPath = shaderPath;
  49618. options.needAlphaBlending = options.needAlphaBlending || false;
  49619. options.needAlphaTesting = options.needAlphaTesting || false;
  49620. options.attributes = options.attributes || ["position", "normal", "uv"];
  49621. options.uniforms = options.uniforms || ["worldViewProjection"];
  49622. options.uniformBuffers = options.uniformBuffers || [];
  49623. options.samplers = options.samplers || [];
  49624. options.defines = options.defines || [];
  49625. _this._options = options;
  49626. return _this;
  49627. }
  49628. ShaderMaterial.prototype.getClassName = function () {
  49629. return "ShaderMaterial";
  49630. };
  49631. ShaderMaterial.prototype.needAlphaBlending = function () {
  49632. return this._options.needAlphaBlending;
  49633. };
  49634. ShaderMaterial.prototype.needAlphaTesting = function () {
  49635. return this._options.needAlphaTesting;
  49636. };
  49637. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  49638. if (this._options.uniforms.indexOf(uniformName) === -1) {
  49639. this._options.uniforms.push(uniformName);
  49640. }
  49641. };
  49642. ShaderMaterial.prototype.setTexture = function (name, texture) {
  49643. if (this._options.samplers.indexOf(name) === -1) {
  49644. this._options.samplers.push(name);
  49645. }
  49646. this._textures[name] = texture;
  49647. return this;
  49648. };
  49649. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  49650. if (this._options.samplers.indexOf(name) === -1) {
  49651. this._options.samplers.push(name);
  49652. }
  49653. this._checkUniform(name);
  49654. this._textureArrays[name] = textures;
  49655. return this;
  49656. };
  49657. ShaderMaterial.prototype.setFloat = function (name, value) {
  49658. this._checkUniform(name);
  49659. this._floats[name] = value;
  49660. return this;
  49661. };
  49662. ShaderMaterial.prototype.setInt = function (name, value) {
  49663. this._checkUniform(name);
  49664. this._ints[name] = value;
  49665. return this;
  49666. };
  49667. ShaderMaterial.prototype.setFloats = function (name, value) {
  49668. this._checkUniform(name);
  49669. this._floatsArrays[name] = value;
  49670. return this;
  49671. };
  49672. ShaderMaterial.prototype.setColor3 = function (name, value) {
  49673. this._checkUniform(name);
  49674. this._colors3[name] = value;
  49675. return this;
  49676. };
  49677. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  49678. this._checkUniform(name);
  49679. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  49680. color.toArray(arr, arr.length);
  49681. return arr;
  49682. }, []);
  49683. return this;
  49684. };
  49685. ShaderMaterial.prototype.setColor4 = function (name, value) {
  49686. this._checkUniform(name);
  49687. this._colors4[name] = value;
  49688. return this;
  49689. };
  49690. ShaderMaterial.prototype.setVector2 = function (name, value) {
  49691. this._checkUniform(name);
  49692. this._vectors2[name] = value;
  49693. return this;
  49694. };
  49695. ShaderMaterial.prototype.setVector3 = function (name, value) {
  49696. this._checkUniform(name);
  49697. this._vectors3[name] = value;
  49698. return this;
  49699. };
  49700. ShaderMaterial.prototype.setVector4 = function (name, value) {
  49701. this._checkUniform(name);
  49702. this._vectors4[name] = value;
  49703. return this;
  49704. };
  49705. ShaderMaterial.prototype.setMatrix = function (name, value) {
  49706. this._checkUniform(name);
  49707. this._matrices[name] = value;
  49708. return this;
  49709. };
  49710. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  49711. this._checkUniform(name);
  49712. this._matrices3x3[name] = value;
  49713. return this;
  49714. };
  49715. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  49716. this._checkUniform(name);
  49717. this._matrices2x2[name] = value;
  49718. return this;
  49719. };
  49720. ShaderMaterial.prototype.setArray2 = function (name, value) {
  49721. this._checkUniform(name);
  49722. this._vectors2Arrays[name] = value;
  49723. return this;
  49724. };
  49725. ShaderMaterial.prototype.setArray3 = function (name, value) {
  49726. this._checkUniform(name);
  49727. this._vectors3Arrays[name] = value;
  49728. return this;
  49729. };
  49730. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  49731. if (!mesh) {
  49732. return true;
  49733. }
  49734. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  49735. return false;
  49736. }
  49737. return false;
  49738. };
  49739. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  49740. var scene = this.getScene();
  49741. var engine = scene.getEngine();
  49742. if (!this.checkReadyOnEveryCall) {
  49743. if (this._renderId === scene.getRenderId()) {
  49744. if (this._checkCache(scene, mesh, useInstances)) {
  49745. return true;
  49746. }
  49747. }
  49748. }
  49749. // Instances
  49750. var defines = [];
  49751. var attribs = [];
  49752. var fallbacks = new BABYLON.EffectFallbacks();
  49753. if (useInstances) {
  49754. defines.push("#define INSTANCES");
  49755. }
  49756. for (var index = 0; index < this._options.defines.length; index++) {
  49757. defines.push(this._options.defines[index]);
  49758. }
  49759. for (var index = 0; index < this._options.attributes.length; index++) {
  49760. attribs.push(this._options.attributes[index]);
  49761. }
  49762. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  49763. attribs.push(BABYLON.VertexBuffer.ColorKind);
  49764. defines.push("#define VERTEXCOLOR");
  49765. }
  49766. // Bones
  49767. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  49768. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  49769. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  49770. if (mesh.numBoneInfluencers > 4) {
  49771. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  49772. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  49773. }
  49774. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  49775. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  49776. fallbacks.addCPUSkinningFallback(0, mesh);
  49777. if (this._options.uniforms.indexOf("mBones") === -1) {
  49778. this._options.uniforms.push("mBones");
  49779. }
  49780. }
  49781. else {
  49782. defines.push("#define NUM_BONE_INFLUENCERS 0");
  49783. }
  49784. // Textures
  49785. for (var name in this._textures) {
  49786. if (!this._textures[name].isReady()) {
  49787. return false;
  49788. }
  49789. }
  49790. // Alpha test
  49791. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  49792. defines.push("#define ALPHATEST");
  49793. }
  49794. var previousEffect = this._effect;
  49795. var join = defines.join("\n");
  49796. this._effect = engine.createEffect(this._shaderPath, {
  49797. attributes: attribs,
  49798. uniformsNames: this._options.uniforms,
  49799. uniformBuffersNames: this._options.uniformBuffers,
  49800. samplers: this._options.samplers,
  49801. defines: join,
  49802. fallbacks: fallbacks,
  49803. onCompiled: this.onCompiled,
  49804. onError: this.onError
  49805. }, engine);
  49806. if (!this._effect.isReady()) {
  49807. return false;
  49808. }
  49809. if (previousEffect !== this._effect) {
  49810. scene.resetCachedMaterial();
  49811. }
  49812. this._renderId = scene.getRenderId();
  49813. return true;
  49814. };
  49815. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  49816. var scene = this.getScene();
  49817. if (!this._effect) {
  49818. return;
  49819. }
  49820. if (this._options.uniforms.indexOf("world") !== -1) {
  49821. this._effect.setMatrix("world", world);
  49822. }
  49823. if (this._options.uniforms.indexOf("worldView") !== -1) {
  49824. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  49825. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  49826. }
  49827. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  49828. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  49829. }
  49830. };
  49831. ShaderMaterial.prototype.bind = function (world, mesh) {
  49832. // Std values
  49833. this.bindOnlyWorldMatrix(world);
  49834. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  49835. if (this._options.uniforms.indexOf("view") !== -1) {
  49836. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  49837. }
  49838. if (this._options.uniforms.indexOf("projection") !== -1) {
  49839. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  49840. }
  49841. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  49842. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  49843. }
  49844. // Bones
  49845. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  49846. var name;
  49847. // Texture
  49848. for (name in this._textures) {
  49849. this._effect.setTexture(name, this._textures[name]);
  49850. }
  49851. // Texture arrays
  49852. for (name in this._textureArrays) {
  49853. this._effect.setTextureArray(name, this._textureArrays[name]);
  49854. }
  49855. // Int
  49856. for (name in this._ints) {
  49857. this._effect.setInt(name, this._ints[name]);
  49858. }
  49859. // Float
  49860. for (name in this._floats) {
  49861. this._effect.setFloat(name, this._floats[name]);
  49862. }
  49863. // Floats
  49864. for (name in this._floatsArrays) {
  49865. this._effect.setArray(name, this._floatsArrays[name]);
  49866. }
  49867. // Color3
  49868. for (name in this._colors3) {
  49869. this._effect.setColor3(name, this._colors3[name]);
  49870. }
  49871. for (name in this._colors3Arrays) {
  49872. this._effect.setArray3(name, this._colors3Arrays[name]);
  49873. }
  49874. // Color4
  49875. for (name in this._colors4) {
  49876. var color = this._colors4[name];
  49877. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49878. }
  49879. // Vector2
  49880. for (name in this._vectors2) {
  49881. this._effect.setVector2(name, this._vectors2[name]);
  49882. }
  49883. // Vector3
  49884. for (name in this._vectors3) {
  49885. this._effect.setVector3(name, this._vectors3[name]);
  49886. }
  49887. // Vector4
  49888. for (name in this._vectors4) {
  49889. this._effect.setVector4(name, this._vectors4[name]);
  49890. }
  49891. // Matrix
  49892. for (name in this._matrices) {
  49893. this._effect.setMatrix(name, this._matrices[name]);
  49894. }
  49895. // Matrix 3x3
  49896. for (name in this._matrices3x3) {
  49897. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  49898. }
  49899. // Matrix 2x2
  49900. for (name in this._matrices2x2) {
  49901. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  49902. }
  49903. // Vector2Array
  49904. for (name in this._vectors2Arrays) {
  49905. this._effect.setArray2(name, this._vectors2Arrays[name]);
  49906. }
  49907. // Vector3Array
  49908. for (name in this._vectors3Arrays) {
  49909. this._effect.setArray3(name, this._vectors3Arrays[name]);
  49910. }
  49911. }
  49912. this._afterBind(mesh);
  49913. };
  49914. ShaderMaterial.prototype.getActiveTextures = function () {
  49915. var activeTextures = _super.prototype.getActiveTextures.call(this);
  49916. for (var name in this._textures) {
  49917. activeTextures.push(this._textures[name]);
  49918. }
  49919. for (var name in this._textureArrays) {
  49920. var array = this._textureArrays[name];
  49921. for (var index = 0; index < array.length; index++) {
  49922. activeTextures.push(array[index]);
  49923. }
  49924. }
  49925. return activeTextures;
  49926. };
  49927. ShaderMaterial.prototype.hasTexture = function (texture) {
  49928. if (_super.prototype.hasTexture.call(this, texture)) {
  49929. return true;
  49930. }
  49931. for (var name in this._textures) {
  49932. if (this._textures[name] === texture) {
  49933. return true;
  49934. }
  49935. }
  49936. for (var name in this._textureArrays) {
  49937. var array = this._textureArrays[name];
  49938. for (var index = 0; index < array.length; index++) {
  49939. if (array[index] === texture) {
  49940. return true;
  49941. }
  49942. }
  49943. }
  49944. return false;
  49945. };
  49946. ShaderMaterial.prototype.clone = function (name) {
  49947. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  49948. return newShaderMaterial;
  49949. };
  49950. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49951. if (forceDisposeTextures) {
  49952. var name;
  49953. for (name in this._textures) {
  49954. this._textures[name].dispose();
  49955. }
  49956. for (name in this._textureArrays) {
  49957. var array = this._textureArrays[name];
  49958. for (var index = 0; index < array.length; index++) {
  49959. array[index].dispose();
  49960. }
  49961. }
  49962. }
  49963. this._textures = {};
  49964. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49965. };
  49966. ShaderMaterial.prototype.serialize = function () {
  49967. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  49968. serializationObject.customType = "BABYLON.ShaderMaterial";
  49969. serializationObject.options = this._options;
  49970. serializationObject.shaderPath = this._shaderPath;
  49971. var name;
  49972. // Texture
  49973. serializationObject.textures = {};
  49974. for (name in this._textures) {
  49975. serializationObject.textures[name] = this._textures[name].serialize();
  49976. }
  49977. // Texture arrays
  49978. serializationObject.textureArrays = {};
  49979. for (name in this._textureArrays) {
  49980. serializationObject.textureArrays[name] = [];
  49981. var array = this._textureArrays[name];
  49982. for (var index = 0; index < array.length; index++) {
  49983. serializationObject.textureArrays[name].push(array[index].serialize());
  49984. }
  49985. }
  49986. // Float
  49987. serializationObject.floats = {};
  49988. for (name in this._floats) {
  49989. serializationObject.floats[name] = this._floats[name];
  49990. }
  49991. // Float s
  49992. serializationObject.FloatArrays = {};
  49993. for (name in this._floatsArrays) {
  49994. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  49995. }
  49996. // Color3
  49997. serializationObject.colors3 = {};
  49998. for (name in this._colors3) {
  49999. serializationObject.colors3[name] = this._colors3[name].asArray();
  50000. }
  50001. // Color3 array
  50002. serializationObject.colors3Arrays = {};
  50003. for (name in this._colors3Arrays) {
  50004. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50005. }
  50006. // Color4
  50007. serializationObject.colors4 = {};
  50008. for (name in this._colors4) {
  50009. serializationObject.colors4[name] = this._colors4[name].asArray();
  50010. }
  50011. // Vector2
  50012. serializationObject.vectors2 = {};
  50013. for (name in this._vectors2) {
  50014. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50015. }
  50016. // Vector3
  50017. serializationObject.vectors3 = {};
  50018. for (name in this._vectors3) {
  50019. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50020. }
  50021. // Vector4
  50022. serializationObject.vectors4 = {};
  50023. for (name in this._vectors4) {
  50024. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50025. }
  50026. // Matrix
  50027. serializationObject.matrices = {};
  50028. for (name in this._matrices) {
  50029. serializationObject.matrices[name] = this._matrices[name].asArray();
  50030. }
  50031. // Matrix 3x3
  50032. serializationObject.matrices3x3 = {};
  50033. for (name in this._matrices3x3) {
  50034. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50035. }
  50036. // Matrix 2x2
  50037. serializationObject.matrices2x2 = {};
  50038. for (name in this._matrices2x2) {
  50039. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50040. }
  50041. // Vector2Array
  50042. serializationObject.vectors2Arrays = {};
  50043. for (name in this._vectors2Arrays) {
  50044. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50045. }
  50046. // Vector3Array
  50047. serializationObject.vectors3Arrays = {};
  50048. for (name in this._vectors3Arrays) {
  50049. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50050. }
  50051. return serializationObject;
  50052. };
  50053. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50054. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50055. var name;
  50056. // Texture
  50057. for (name in source.textures) {
  50058. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50059. }
  50060. // Texture arrays
  50061. for (name in source.textureArrays) {
  50062. var array = source.textureArrays[name];
  50063. var textureArray = new Array();
  50064. for (var index = 0; index < array.length; index++) {
  50065. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50066. }
  50067. material.setTextureArray(name, textureArray);
  50068. }
  50069. // Float
  50070. for (name in source.floats) {
  50071. material.setFloat(name, source.floats[name]);
  50072. }
  50073. // Float s
  50074. for (name in source.floatsArrays) {
  50075. material.setFloats(name, source.floatsArrays[name]);
  50076. }
  50077. // Color3
  50078. for (name in source.colors3) {
  50079. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50080. }
  50081. // Color3 arrays
  50082. for (name in source.colors3Arrays) {
  50083. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50084. if (i % 3 === 0) {
  50085. arr.push([num]);
  50086. }
  50087. else {
  50088. arr[arr.length - 1].push(num);
  50089. }
  50090. return arr;
  50091. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50092. material.setColor3Array(name, colors);
  50093. }
  50094. // Color4
  50095. for (name in source.colors4) {
  50096. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50097. }
  50098. // Vector2
  50099. for (name in source.vectors2) {
  50100. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50101. }
  50102. // Vector3
  50103. for (name in source.vectors3) {
  50104. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50105. }
  50106. // Vector4
  50107. for (name in source.vectors4) {
  50108. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50109. }
  50110. // Matrix
  50111. for (name in source.matrices) {
  50112. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50113. }
  50114. // Matrix 3x3
  50115. for (name in source.matrices3x3) {
  50116. material.setMatrix3x3(name, source.matrices3x3[name]);
  50117. }
  50118. // Matrix 2x2
  50119. for (name in source.matrices2x2) {
  50120. material.setMatrix2x2(name, source.matrices2x2[name]);
  50121. }
  50122. // Vector2Array
  50123. for (name in source.vectors2Arrays) {
  50124. material.setArray2(name, source.vectors2Arrays[name]);
  50125. }
  50126. // Vector3Array
  50127. for (name in source.vectors3Arrays) {
  50128. material.setArray3(name, source.vectors3Arrays[name]);
  50129. }
  50130. return material;
  50131. };
  50132. return ShaderMaterial;
  50133. }(BABYLON.Material));
  50134. BABYLON.ShaderMaterial = ShaderMaterial;
  50135. })(BABYLON || (BABYLON = {}));
  50136. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50137. var BABYLON;
  50138. (function (BABYLON) {
  50139. var GroundMesh = /** @class */ (function (_super) {
  50140. __extends(GroundMesh, _super);
  50141. function GroundMesh(name, scene) {
  50142. var _this = _super.call(this, name, scene) || this;
  50143. _this.generateOctree = false;
  50144. return _this;
  50145. }
  50146. GroundMesh.prototype.getClassName = function () {
  50147. return "GroundMesh";
  50148. };
  50149. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50150. get: function () {
  50151. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50157. get: function () {
  50158. return this._subdivisionsX;
  50159. },
  50160. enumerable: true,
  50161. configurable: true
  50162. });
  50163. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50164. get: function () {
  50165. return this._subdivisionsY;
  50166. },
  50167. enumerable: true,
  50168. configurable: true
  50169. });
  50170. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50171. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50172. this._subdivisionsX = chunksCount;
  50173. this._subdivisionsY = chunksCount;
  50174. this.subdivide(chunksCount);
  50175. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50176. };
  50177. /**
  50178. * Returns a height (y) value in the Worl system :
  50179. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50180. * Returns the ground y position if (x, z) are outside the ground surface.
  50181. */
  50182. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50183. var world = this.getWorldMatrix();
  50184. var invMat = BABYLON.Tmp.Matrix[5];
  50185. world.invertToRef(invMat);
  50186. var tmpVect = BABYLON.Tmp.Vector3[8];
  50187. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50188. x = tmpVect.x;
  50189. z = tmpVect.z;
  50190. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50191. return this.position.y;
  50192. }
  50193. if (!this._heightQuads || this._heightQuads.length == 0) {
  50194. this._initHeightQuads();
  50195. this._computeHeightQuads();
  50196. }
  50197. var facet = this._getFacetAt(x, z);
  50198. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50199. // return y in the World system
  50200. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50201. return tmpVect.y;
  50202. };
  50203. /**
  50204. * Returns a normalized vector (Vector3) orthogonal to the ground
  50205. * at the ground coordinates (x, z) expressed in the World system.
  50206. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50207. */
  50208. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50209. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50210. this.getNormalAtCoordinatesToRef(x, z, normal);
  50211. return normal;
  50212. };
  50213. /**
  50214. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50215. * at the ground coordinates (x, z) expressed in the World system.
  50216. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50217. * Returns the GroundMesh.
  50218. */
  50219. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50220. var world = this.getWorldMatrix();
  50221. var tmpMat = BABYLON.Tmp.Matrix[5];
  50222. world.invertToRef(tmpMat);
  50223. var tmpVect = BABYLON.Tmp.Vector3[8];
  50224. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50225. x = tmpVect.x;
  50226. z = tmpVect.z;
  50227. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50228. return this;
  50229. }
  50230. if (!this._heightQuads || this._heightQuads.length == 0) {
  50231. this._initHeightQuads();
  50232. this._computeHeightQuads();
  50233. }
  50234. var facet = this._getFacetAt(x, z);
  50235. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  50236. return this;
  50237. };
  50238. /**
  50239. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  50240. * if the ground has been updated.
  50241. * This can be used in the render loop.
  50242. * Returns the GroundMesh.
  50243. */
  50244. GroundMesh.prototype.updateCoordinateHeights = function () {
  50245. if (!this._heightQuads || this._heightQuads.length == 0) {
  50246. this._initHeightQuads();
  50247. }
  50248. this._computeHeightQuads();
  50249. return this;
  50250. };
  50251. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  50252. GroundMesh.prototype._getFacetAt = function (x, z) {
  50253. // retrieve col and row from x, z coordinates in the ground local system
  50254. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  50255. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  50256. var quad = this._heightQuads[row * this._subdivisionsX + col];
  50257. var facet;
  50258. if (z < quad.slope.x * x + quad.slope.y) {
  50259. facet = quad.facet1;
  50260. }
  50261. else {
  50262. facet = quad.facet2;
  50263. }
  50264. return facet;
  50265. };
  50266. // Creates and populates the heightMap array with "facet" elements :
  50267. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  50268. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50269. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50270. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50271. // Returns the GroundMesh.
  50272. GroundMesh.prototype._initHeightQuads = function () {
  50273. var subdivisionsX = this._subdivisionsX;
  50274. var subdivisionsY = this._subdivisionsY;
  50275. this._heightQuads = new Array();
  50276. for (var row = 0; row < subdivisionsY; row++) {
  50277. for (var col = 0; col < subdivisionsX; col++) {
  50278. 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) };
  50279. this._heightQuads[row * subdivisionsX + col] = quad;
  50280. }
  50281. }
  50282. return this;
  50283. };
  50284. // Compute each quad element values and update the the heightMap array :
  50285. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50286. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50287. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50288. // Returns the GroundMesh.
  50289. GroundMesh.prototype._computeHeightQuads = function () {
  50290. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50291. if (!positions) {
  50292. return this;
  50293. }
  50294. var v1 = BABYLON.Tmp.Vector3[3];
  50295. var v2 = BABYLON.Tmp.Vector3[2];
  50296. var v3 = BABYLON.Tmp.Vector3[1];
  50297. var v4 = BABYLON.Tmp.Vector3[0];
  50298. var v1v2 = BABYLON.Tmp.Vector3[4];
  50299. var v1v3 = BABYLON.Tmp.Vector3[5];
  50300. var v1v4 = BABYLON.Tmp.Vector3[6];
  50301. var norm1 = BABYLON.Tmp.Vector3[7];
  50302. var norm2 = BABYLON.Tmp.Vector3[8];
  50303. var i = 0;
  50304. var j = 0;
  50305. var k = 0;
  50306. var cd = 0; // 2D slope coefficient : z = cd * x + h
  50307. var h = 0;
  50308. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  50309. var d2 = 0;
  50310. var subdivisionsX = this._subdivisionsX;
  50311. var subdivisionsY = this._subdivisionsY;
  50312. for (var row = 0; row < subdivisionsY; row++) {
  50313. for (var col = 0; col < subdivisionsX; col++) {
  50314. i = col * 3;
  50315. j = row * (subdivisionsX + 1) * 3;
  50316. k = (row + 1) * (subdivisionsX + 1) * 3;
  50317. v1.x = positions[j + i];
  50318. v1.y = positions[j + i + 1];
  50319. v1.z = positions[j + i + 2];
  50320. v2.x = positions[j + i + 3];
  50321. v2.y = positions[j + i + 4];
  50322. v2.z = positions[j + i + 5];
  50323. v3.x = positions[k + i];
  50324. v3.y = positions[k + i + 1];
  50325. v3.z = positions[k + i + 2];
  50326. v4.x = positions[k + i + 3];
  50327. v4.y = positions[k + i + 4];
  50328. v4.z = positions[k + i + 5];
  50329. // 2D slope V1V4
  50330. cd = (v4.z - v1.z) / (v4.x - v1.x);
  50331. h = v1.z - cd * v1.x; // v1 belongs to the slope
  50332. // facet equations :
  50333. // we compute each facet normal vector
  50334. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  50335. // we compute the value d by applying the equation to v1 which belongs to the plane
  50336. // then we store the facet equation in a Vector4
  50337. v2.subtractToRef(v1, v1v2);
  50338. v3.subtractToRef(v1, v1v3);
  50339. v4.subtractToRef(v1, v1v4);
  50340. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  50341. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  50342. norm1.normalize();
  50343. norm2.normalize();
  50344. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  50345. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  50346. var quad = this._heightQuads[row * subdivisionsX + col];
  50347. quad.slope.copyFromFloats(cd, h);
  50348. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  50349. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  50350. }
  50351. }
  50352. return this;
  50353. };
  50354. GroundMesh.prototype.serialize = function (serializationObject) {
  50355. _super.prototype.serialize.call(this, serializationObject);
  50356. serializationObject.subdivisionsX = this._subdivisionsX;
  50357. serializationObject.subdivisionsY = this._subdivisionsY;
  50358. serializationObject.minX = this._minX;
  50359. serializationObject.maxX = this._maxX;
  50360. serializationObject.minZ = this._minZ;
  50361. serializationObject.maxZ = this._maxZ;
  50362. serializationObject.width = this._width;
  50363. serializationObject.height = this._height;
  50364. };
  50365. GroundMesh.Parse = function (parsedMesh, scene) {
  50366. var result = new GroundMesh(parsedMesh.name, scene);
  50367. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  50368. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  50369. result._minX = parsedMesh.minX;
  50370. result._maxX = parsedMesh.maxX;
  50371. result._minZ = parsedMesh.minZ;
  50372. result._maxZ = parsedMesh.maxZ;
  50373. result._width = parsedMesh.width;
  50374. result._height = parsedMesh.height;
  50375. return result;
  50376. };
  50377. return GroundMesh;
  50378. }(BABYLON.Mesh));
  50379. BABYLON.GroundMesh = GroundMesh;
  50380. })(BABYLON || (BABYLON = {}));
  50381. //# sourceMappingURL=babylon.groundMesh.js.map
  50382. var BABYLON;
  50383. (function (BABYLON) {
  50384. /**
  50385. * Creates an instance based on a source mesh.
  50386. */
  50387. var InstancedMesh = /** @class */ (function (_super) {
  50388. __extends(InstancedMesh, _super);
  50389. function InstancedMesh(name, source) {
  50390. var _this = _super.call(this, name, source.getScene()) || this;
  50391. source.instances.push(_this);
  50392. _this._sourceMesh = source;
  50393. _this.position.copyFrom(source.position);
  50394. _this.rotation.copyFrom(source.rotation);
  50395. _this.scaling.copyFrom(source.scaling);
  50396. if (source.rotationQuaternion) {
  50397. _this.rotationQuaternion = source.rotationQuaternion.clone();
  50398. }
  50399. _this.infiniteDistance = source.infiniteDistance;
  50400. _this.setPivotMatrix(source.getPivotMatrix());
  50401. _this.refreshBoundingInfo();
  50402. _this._syncSubMeshes();
  50403. return _this;
  50404. }
  50405. /**
  50406. * Returns the string "InstancedMesh".
  50407. */
  50408. InstancedMesh.prototype.getClassName = function () {
  50409. return "InstancedMesh";
  50410. };
  50411. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  50412. // Methods
  50413. get: function () {
  50414. return this._sourceMesh.receiveShadows;
  50415. },
  50416. enumerable: true,
  50417. configurable: true
  50418. });
  50419. Object.defineProperty(InstancedMesh.prototype, "material", {
  50420. get: function () {
  50421. return this._sourceMesh.material;
  50422. },
  50423. enumerable: true,
  50424. configurable: true
  50425. });
  50426. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  50427. get: function () {
  50428. return this._sourceMesh.visibility;
  50429. },
  50430. enumerable: true,
  50431. configurable: true
  50432. });
  50433. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  50434. get: function () {
  50435. return this._sourceMesh.skeleton;
  50436. },
  50437. enumerable: true,
  50438. configurable: true
  50439. });
  50440. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  50441. get: function () {
  50442. return this._sourceMesh.renderingGroupId;
  50443. },
  50444. enumerable: true,
  50445. configurable: true
  50446. });
  50447. /**
  50448. * Returns the total number of vertices (integer).
  50449. */
  50450. InstancedMesh.prototype.getTotalVertices = function () {
  50451. return this._sourceMesh.getTotalVertices();
  50452. };
  50453. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  50454. get: function () {
  50455. return this._sourceMesh;
  50456. },
  50457. enumerable: true,
  50458. configurable: true
  50459. });
  50460. /**
  50461. * Is this node ready to be used/rendered
  50462. * @return {boolean} is it ready
  50463. */
  50464. InstancedMesh.prototype.isReady = function () {
  50465. return this._sourceMesh.isReady(true);
  50466. };
  50467. /**
  50468. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  50469. */
  50470. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  50471. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  50472. };
  50473. /**
  50474. * Sets the vertex data of the mesh geometry for the requested `kind`.
  50475. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  50476. * The `data` are either a numeric array either a Float32Array.
  50477. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  50478. * 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).
  50479. * Note that a new underlying VertexBuffer object is created each call.
  50480. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  50481. *
  50482. * Possible `kind` values :
  50483. * - BABYLON.VertexBuffer.PositionKind
  50484. * - BABYLON.VertexBuffer.UVKind
  50485. * - BABYLON.VertexBuffer.UV2Kind
  50486. * - BABYLON.VertexBuffer.UV3Kind
  50487. * - BABYLON.VertexBuffer.UV4Kind
  50488. * - BABYLON.VertexBuffer.UV5Kind
  50489. * - BABYLON.VertexBuffer.UV6Kind
  50490. * - BABYLON.VertexBuffer.ColorKind
  50491. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50492. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50493. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50494. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50495. *
  50496. * Returns the Mesh.
  50497. */
  50498. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  50499. if (this.sourceMesh) {
  50500. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  50501. }
  50502. return this.sourceMesh;
  50503. };
  50504. /**
  50505. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  50506. * If the mesh has no geometry, it is simply returned as it is.
  50507. * The `data` are either a numeric array either a Float32Array.
  50508. * No new underlying VertexBuffer object is created.
  50509. * 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.
  50510. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  50511. *
  50512. * Possible `kind` values :
  50513. * - BABYLON.VertexBuffer.PositionKind
  50514. * - BABYLON.VertexBuffer.UVKind
  50515. * - BABYLON.VertexBuffer.UV2Kind
  50516. * - BABYLON.VertexBuffer.UV3Kind
  50517. * - BABYLON.VertexBuffer.UV4Kind
  50518. * - BABYLON.VertexBuffer.UV5Kind
  50519. * - BABYLON.VertexBuffer.UV6Kind
  50520. * - BABYLON.VertexBuffer.ColorKind
  50521. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50522. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50523. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50524. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50525. *
  50526. * Returns the Mesh.
  50527. */
  50528. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  50529. if (this.sourceMesh) {
  50530. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  50531. }
  50532. return this.sourceMesh;
  50533. };
  50534. /**
  50535. * Sets the mesh indices.
  50536. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  50537. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  50538. * This method creates a new index buffer each call.
  50539. * Returns the Mesh.
  50540. */
  50541. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  50542. if (totalVertices === void 0) { totalVertices = null; }
  50543. if (this.sourceMesh) {
  50544. this.sourceMesh.setIndices(indices, totalVertices);
  50545. }
  50546. return this.sourceMesh;
  50547. };
  50548. /**
  50549. * Boolean : True if the mesh owns the requested kind of data.
  50550. */
  50551. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  50552. return this._sourceMesh.isVerticesDataPresent(kind);
  50553. };
  50554. /**
  50555. * Returns an array of indices (IndicesArray).
  50556. */
  50557. InstancedMesh.prototype.getIndices = function () {
  50558. return this._sourceMesh.getIndices();
  50559. };
  50560. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  50561. get: function () {
  50562. return this._sourceMesh._positions;
  50563. },
  50564. enumerable: true,
  50565. configurable: true
  50566. });
  50567. /**
  50568. * Sets a new updated BoundingInfo to the mesh.
  50569. * Returns the mesh.
  50570. */
  50571. InstancedMesh.prototype.refreshBoundingInfo = function () {
  50572. var meshBB = this._sourceMesh.getBoundingInfo();
  50573. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  50574. this._updateBoundingInfo();
  50575. return this;
  50576. };
  50577. InstancedMesh.prototype._preActivate = function () {
  50578. if (this._currentLOD) {
  50579. this._currentLOD._preActivate();
  50580. }
  50581. return this;
  50582. };
  50583. InstancedMesh.prototype._activate = function (renderId) {
  50584. if (this._currentLOD) {
  50585. this._currentLOD._registerInstanceForRenderId(this, renderId);
  50586. }
  50587. return this;
  50588. };
  50589. /**
  50590. * Returns the current associated LOD AbstractMesh.
  50591. */
  50592. InstancedMesh.prototype.getLOD = function (camera) {
  50593. if (!camera) {
  50594. return this;
  50595. }
  50596. var boundingInfo = this.getBoundingInfo();
  50597. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  50598. if (this._currentLOD === this.sourceMesh) {
  50599. return this;
  50600. }
  50601. return this._currentLOD;
  50602. };
  50603. InstancedMesh.prototype._syncSubMeshes = function () {
  50604. this.releaseSubMeshes();
  50605. if (this._sourceMesh.subMeshes) {
  50606. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  50607. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  50608. }
  50609. }
  50610. return this;
  50611. };
  50612. InstancedMesh.prototype._generatePointsArray = function () {
  50613. return this._sourceMesh._generatePointsArray();
  50614. };
  50615. /**
  50616. * Creates a new InstancedMesh from the current mesh.
  50617. * - name (string) : the cloned mesh name
  50618. * - newParent (optional Node) : the optional Node to parent the clone to.
  50619. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  50620. *
  50621. * Returns the clone.
  50622. */
  50623. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50624. var result = this._sourceMesh.createInstance(name);
  50625. // Deep copy
  50626. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  50627. // Bounding info
  50628. this.refreshBoundingInfo();
  50629. // Parent
  50630. if (newParent) {
  50631. result.parent = newParent;
  50632. }
  50633. if (!doNotCloneChildren) {
  50634. // Children
  50635. for (var index = 0; index < this.getScene().meshes.length; index++) {
  50636. var mesh = this.getScene().meshes[index];
  50637. if (mesh.parent === this) {
  50638. mesh.clone(mesh.name, result);
  50639. }
  50640. }
  50641. }
  50642. result.computeWorldMatrix(true);
  50643. return result;
  50644. };
  50645. /**
  50646. * Disposes the InstancedMesh.
  50647. * Returns nothing.
  50648. */
  50649. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  50650. // Remove from mesh
  50651. var index = this._sourceMesh.instances.indexOf(this);
  50652. this._sourceMesh.instances.splice(index, 1);
  50653. _super.prototype.dispose.call(this, doNotRecurse);
  50654. };
  50655. return InstancedMesh;
  50656. }(BABYLON.AbstractMesh));
  50657. BABYLON.InstancedMesh = InstancedMesh;
  50658. })(BABYLON || (BABYLON = {}));
  50659. //# sourceMappingURL=babylon.instancedMesh.js.map
  50660. var BABYLON;
  50661. (function (BABYLON) {
  50662. var LinesMesh = /** @class */ (function (_super) {
  50663. __extends(LinesMesh, _super);
  50664. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  50665. if (scene === void 0) { scene = null; }
  50666. if (parent === void 0) { parent = null; }
  50667. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  50668. _this.useVertexColor = useVertexColor;
  50669. _this.useVertexAlpha = useVertexAlpha;
  50670. _this.color = new BABYLON.Color3(1, 1, 1);
  50671. _this.alpha = 1;
  50672. if (source) {
  50673. _this.color = source.color.clone();
  50674. _this.alpha = source.alpha;
  50675. _this.useVertexColor = source.useVertexColor;
  50676. _this.useVertexAlpha = source.useVertexAlpha;
  50677. }
  50678. _this._intersectionThreshold = 0.1;
  50679. var defines = [];
  50680. var options = {
  50681. attributes: [BABYLON.VertexBuffer.PositionKind],
  50682. uniforms: ["world", "viewProjection"],
  50683. needAlphaBlending: true,
  50684. defines: defines
  50685. };
  50686. if (useVertexAlpha === false) {
  50687. options.needAlphaBlending = false;
  50688. }
  50689. if (!useVertexColor) {
  50690. options.uniforms.push("color");
  50691. }
  50692. else {
  50693. options.defines.push("#define VERTEXCOLOR");
  50694. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  50695. }
  50696. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  50697. return _this;
  50698. }
  50699. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  50700. /**
  50701. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50702. * This margin is expressed in world space coordinates, so its value may vary.
  50703. * Default value is 0.1
  50704. * @returns the intersection Threshold value.
  50705. */
  50706. get: function () {
  50707. return this._intersectionThreshold;
  50708. },
  50709. /**
  50710. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  50711. * This margin is expressed in world space coordinates, so its value may vary.
  50712. * @param value the new threshold to apply
  50713. */
  50714. set: function (value) {
  50715. if (this._intersectionThreshold === value) {
  50716. return;
  50717. }
  50718. this._intersectionThreshold = value;
  50719. if (this.geometry) {
  50720. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  50721. }
  50722. },
  50723. enumerable: true,
  50724. configurable: true
  50725. });
  50726. /**
  50727. * Returns the string "LineMesh"
  50728. */
  50729. LinesMesh.prototype.getClassName = function () {
  50730. return "LinesMesh";
  50731. };
  50732. Object.defineProperty(LinesMesh.prototype, "material", {
  50733. get: function () {
  50734. return this._colorShader;
  50735. },
  50736. set: function (value) {
  50737. // Do nothing
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  50743. get: function () {
  50744. return false;
  50745. },
  50746. enumerable: true,
  50747. configurable: true
  50748. });
  50749. LinesMesh.prototype.createInstance = function (name) {
  50750. throw new Error("LinesMeshes do not support createInstance.");
  50751. };
  50752. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  50753. if (!this._geometry) {
  50754. return this;
  50755. }
  50756. // VBOs
  50757. this._geometry._bind(this._colorShader.getEffect());
  50758. // Color
  50759. if (!this.useVertexColor) {
  50760. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  50761. }
  50762. return this;
  50763. };
  50764. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  50765. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  50766. return this;
  50767. }
  50768. var engine = this.getScene().getEngine();
  50769. // Draw order
  50770. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  50771. return this;
  50772. };
  50773. LinesMesh.prototype.dispose = function (doNotRecurse) {
  50774. this._colorShader.dispose();
  50775. _super.prototype.dispose.call(this, doNotRecurse);
  50776. };
  50777. /**
  50778. * Returns a new LineMesh object cloned from the current one.
  50779. */
  50780. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  50781. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  50782. };
  50783. return LinesMesh;
  50784. }(BABYLON.Mesh));
  50785. BABYLON.LinesMesh = LinesMesh;
  50786. })(BABYLON || (BABYLON = {}));
  50787. //# sourceMappingURL=babylon.linesMesh.js.map
  50788. var BABYLON;
  50789. (function (BABYLON) {
  50790. var MeshBuilder = /** @class */ (function () {
  50791. function MeshBuilder() {
  50792. }
  50793. MeshBuilder.updateSideOrientation = function (orientation) {
  50794. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  50795. return BABYLON.Mesh.DOUBLESIDE;
  50796. }
  50797. if (orientation === undefined || orientation === null) {
  50798. return BABYLON.Mesh.FRONTSIDE;
  50799. }
  50800. return orientation;
  50801. };
  50802. /**
  50803. * Creates a box mesh.
  50804. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  50805. * The parameter `size` sets the size (float) of each box side (default 1).
  50806. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  50807. * 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).
  50808. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50809. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50810. * 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).
  50811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50813. */
  50814. MeshBuilder.CreateBox = function (name, options, scene) {
  50815. if (scene === void 0) { scene = null; }
  50816. var box = new BABYLON.Mesh(name, scene);
  50817. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50818. box._originalBuilderSideOrientation = options.sideOrientation;
  50819. var vertexData = BABYLON.VertexData.CreateBox(options);
  50820. vertexData.applyToMesh(box, options.updatable);
  50821. return box;
  50822. };
  50823. /**
  50824. * Creates a sphere mesh.
  50825. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  50826. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  50827. * 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`).
  50828. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  50829. * 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
  50830. * 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).
  50831. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50832. * 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).
  50833. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50835. */
  50836. MeshBuilder.CreateSphere = function (name, options, scene) {
  50837. var sphere = new BABYLON.Mesh(name, scene);
  50838. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50839. sphere._originalBuilderSideOrientation = options.sideOrientation;
  50840. var vertexData = BABYLON.VertexData.CreateSphere(options);
  50841. vertexData.applyToMesh(sphere, options.updatable);
  50842. return sphere;
  50843. };
  50844. /**
  50845. * Creates a plane polygonal mesh. By default, this is a disc.
  50846. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  50847. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  50848. * 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.
  50849. * 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
  50850. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50851. * 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).
  50852. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50854. */
  50855. MeshBuilder.CreateDisc = function (name, options, scene) {
  50856. if (scene === void 0) { scene = null; }
  50857. var disc = new BABYLON.Mesh(name, scene);
  50858. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50859. disc._originalBuilderSideOrientation = options.sideOrientation;
  50860. var vertexData = BABYLON.VertexData.CreateDisc(options);
  50861. vertexData.applyToMesh(disc, options.updatable);
  50862. return disc;
  50863. };
  50864. /**
  50865. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  50866. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  50867. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  50868. * 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`).
  50869. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  50870. * 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.
  50871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50872. * 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).
  50873. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50874. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50875. */
  50876. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  50877. var sphere = new BABYLON.Mesh(name, scene);
  50878. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50879. sphere._originalBuilderSideOrientation = options.sideOrientation;
  50880. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  50881. vertexData.applyToMesh(sphere, options.updatable);
  50882. return sphere;
  50883. };
  50884. ;
  50885. /**
  50886. * Creates a ribbon mesh.
  50887. * 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.
  50888. *
  50889. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  50890. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  50891. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  50892. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  50893. * 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.
  50894. * 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.
  50895. * 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
  50896. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50897. * 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).
  50898. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50899. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50900. * 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.
  50901. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  50902. * 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
  50903. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  50904. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  50905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50906. */
  50907. MeshBuilder.CreateRibbon = function (name, options, scene) {
  50908. if (scene === void 0) { scene = null; }
  50909. var pathArray = options.pathArray;
  50910. var closeArray = options.closeArray;
  50911. var closePath = options.closePath;
  50912. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50913. var instance = options.instance;
  50914. var updatable = options.updatable;
  50915. if (instance) {
  50916. // positionFunction : ribbon case
  50917. // only pathArray and sideOrientation parameters are taken into account for positions update
  50918. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  50919. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  50920. var positionFunction = function (positions) {
  50921. var minlg = pathArray[0].length;
  50922. var i = 0;
  50923. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  50924. for (var si = 1; si <= ns; si++) {
  50925. for (var p = 0; p < pathArray.length; p++) {
  50926. var path = pathArray[p];
  50927. var l = path.length;
  50928. minlg = (minlg < l) ? minlg : l;
  50929. var j = 0;
  50930. while (j < minlg) {
  50931. positions[i] = path[j].x;
  50932. positions[i + 1] = path[j].y;
  50933. positions[i + 2] = path[j].z;
  50934. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  50935. BABYLON.Tmp.Vector3[0].x = path[j].x;
  50936. }
  50937. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  50938. BABYLON.Tmp.Vector3[1].x = path[j].x;
  50939. }
  50940. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  50941. BABYLON.Tmp.Vector3[0].y = path[j].y;
  50942. }
  50943. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  50944. BABYLON.Tmp.Vector3[1].y = path[j].y;
  50945. }
  50946. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  50947. BABYLON.Tmp.Vector3[0].z = path[j].z;
  50948. }
  50949. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  50950. BABYLON.Tmp.Vector3[1].z = path[j].z;
  50951. }
  50952. j++;
  50953. i += 3;
  50954. }
  50955. if (instance._closePath) {
  50956. positions[i] = path[0].x;
  50957. positions[i + 1] = path[0].y;
  50958. positions[i + 2] = path[0].z;
  50959. i += 3;
  50960. }
  50961. }
  50962. }
  50963. };
  50964. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50965. positionFunction(positions);
  50966. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  50967. instance._boundingInfo.update(instance._worldMatrix);
  50968. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  50969. if (options.colors) {
  50970. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50971. for (var c = 0; c < options.colors.length; c++) {
  50972. colors[c * 4] = options.colors[c].r;
  50973. colors[c * 4 + 1] = options.colors[c].g;
  50974. colors[c * 4 + 2] = options.colors[c].b;
  50975. colors[c * 4 + 3] = options.colors[c].a;
  50976. }
  50977. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  50978. }
  50979. if (options.uvs) {
  50980. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50981. for (var i = 0; i < options.uvs.length; i++) {
  50982. uvs[i * 2] = options.uvs[i].x;
  50983. uvs[i * 2 + 1] = options.uvs[i].y;
  50984. }
  50985. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  50986. }
  50987. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  50988. var indices = instance.getIndices();
  50989. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50990. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  50991. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  50992. if (instance._closePath) {
  50993. var indexFirst = 0;
  50994. var indexLast = 0;
  50995. for (var p = 0; p < pathArray.length; p++) {
  50996. indexFirst = instance._idx[p] * 3;
  50997. if (p + 1 < pathArray.length) {
  50998. indexLast = (instance._idx[p + 1] - 1) * 3;
  50999. }
  51000. else {
  51001. indexLast = normals.length - 3;
  51002. }
  51003. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51004. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51005. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51006. normals[indexLast] = normals[indexFirst];
  51007. normals[indexLast + 1] = normals[indexFirst + 1];
  51008. normals[indexLast + 2] = normals[indexFirst + 2];
  51009. }
  51010. }
  51011. if (!(instance.areNormalsFrozen)) {
  51012. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51013. }
  51014. }
  51015. return instance;
  51016. }
  51017. else {
  51018. var ribbon = new BABYLON.Mesh(name, scene);
  51019. ribbon._originalBuilderSideOrientation = sideOrientation;
  51020. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51021. if (closePath) {
  51022. ribbon._idx = vertexData._idx;
  51023. }
  51024. ribbon._closePath = closePath;
  51025. ribbon._closeArray = closeArray;
  51026. vertexData.applyToMesh(ribbon, updatable);
  51027. return ribbon;
  51028. }
  51029. };
  51030. /**
  51031. * Creates a cylinder or a cone mesh.
  51032. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51033. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51034. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51035. * 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.
  51036. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51037. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51038. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51039. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51040. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51041. * 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).
  51042. * 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
  51043. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51044. * 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
  51045. * 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.
  51046. * If `enclose` is false, a ring surface is one element.
  51047. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51048. * 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
  51049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51050. * 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).
  51051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51053. */
  51054. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51055. var cylinder = new BABYLON.Mesh(name, scene);
  51056. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51057. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51058. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51059. vertexData.applyToMesh(cylinder, options.updatable);
  51060. return cylinder;
  51061. };
  51062. /**
  51063. * Creates a torus mesh.
  51064. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51065. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51066. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51067. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51068. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51069. * 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).
  51070. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51071. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51072. */
  51073. MeshBuilder.CreateTorus = function (name, options, scene) {
  51074. var torus = new BABYLON.Mesh(name, scene);
  51075. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51076. torus._originalBuilderSideOrientation = options.sideOrientation;
  51077. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51078. vertexData.applyToMesh(torus, options.updatable);
  51079. return torus;
  51080. };
  51081. /**
  51082. * Creates a torus knot mesh.
  51083. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51084. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51085. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51086. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51087. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51088. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51089. * 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).
  51090. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51091. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51092. */
  51093. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51094. var torusKnot = new BABYLON.Mesh(name, scene);
  51095. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51096. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51097. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51098. vertexData.applyToMesh(torusKnot, options.updatable);
  51099. return torusKnot;
  51100. };
  51101. /**
  51102. * Creates a line system mesh.
  51103. * A line system is a pool of many lines gathered in a single mesh.
  51104. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51105. * 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.
  51106. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51107. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51108. * 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
  51109. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51110. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51111. * 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
  51112. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51113. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51114. */
  51115. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51116. var instance = options.instance;
  51117. var lines = options.lines;
  51118. var colors = options.colors;
  51119. if (instance) {
  51120. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51121. var vertexColor;
  51122. var lineColors;
  51123. if (colors) {
  51124. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51125. }
  51126. var i = 0;
  51127. var c = 0;
  51128. for (var l = 0; l < lines.length; l++) {
  51129. var points = lines[l];
  51130. for (var p = 0; p < points.length; p++) {
  51131. positions[i] = points[p].x;
  51132. positions[i + 1] = points[p].y;
  51133. positions[i + 2] = points[p].z;
  51134. if (colors && vertexColor) {
  51135. lineColors = colors[l];
  51136. vertexColor[c] = lineColors[p].r;
  51137. vertexColor[c + 1] = lineColors[p].g;
  51138. vertexColor[c + 2] = lineColors[p].b;
  51139. vertexColor[c + 3] = lineColors[p].a;
  51140. c += 4;
  51141. }
  51142. i += 3;
  51143. }
  51144. }
  51145. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51146. if (colors && vertexColor) {
  51147. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51148. }
  51149. return instance;
  51150. }
  51151. // line system creation
  51152. var useVertexColor = (colors) ? true : false;
  51153. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51154. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51155. vertexData.applyToMesh(lineSystem, options.updatable);
  51156. return lineSystem;
  51157. };
  51158. /**
  51159. * Creates a line mesh.
  51160. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51161. * 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.
  51162. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51163. * The parameter `points` is an array successive Vector3.
  51164. * 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
  51165. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51166. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51167. * When updating an instance, remember that only point positions can change, not the number of points.
  51168. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51169. */
  51170. MeshBuilder.CreateLines = function (name, options, scene) {
  51171. if (scene === void 0) { scene = null; }
  51172. var colors = (options.colors) ? [options.colors] : null;
  51173. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51174. return lines;
  51175. };
  51176. /**
  51177. * Creates a dashed line mesh.
  51178. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51179. * 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.
  51180. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51181. * The parameter `points` is an array successive Vector3.
  51182. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51183. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51184. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51185. * 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
  51186. * When updating an instance, remember that only point positions can change, not the number of points.
  51187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51188. */
  51189. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51190. if (scene === void 0) { scene = null; }
  51191. var points = options.points;
  51192. var instance = options.instance;
  51193. var gapSize = options.gapSize || 1;
  51194. var dashSize = options.dashSize || 3;
  51195. if (instance) {
  51196. var positionFunction = function (positions) {
  51197. var curvect = BABYLON.Vector3.Zero();
  51198. var nbSeg = positions.length / 6;
  51199. var lg = 0;
  51200. var nb = 0;
  51201. var shft = 0;
  51202. var dashshft = 0;
  51203. var curshft = 0;
  51204. var p = 0;
  51205. var i = 0;
  51206. var j = 0;
  51207. for (i = 0; i < points.length - 1; i++) {
  51208. points[i + 1].subtractToRef(points[i], curvect);
  51209. lg += curvect.length();
  51210. }
  51211. shft = lg / nbSeg;
  51212. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51213. for (i = 0; i < points.length - 1; i++) {
  51214. points[i + 1].subtractToRef(points[i], curvect);
  51215. nb = Math.floor(curvect.length() / shft);
  51216. curvect.normalize();
  51217. j = 0;
  51218. while (j < nb && p < positions.length) {
  51219. curshft = shft * j;
  51220. positions[p] = points[i].x + curshft * curvect.x;
  51221. positions[p + 1] = points[i].y + curshft * curvect.y;
  51222. positions[p + 2] = points[i].z + curshft * curvect.z;
  51223. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51224. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51225. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51226. p += 6;
  51227. j++;
  51228. }
  51229. }
  51230. while (p < positions.length) {
  51231. positions[p] = points[i].x;
  51232. positions[p + 1] = points[i].y;
  51233. positions[p + 2] = points[i].z;
  51234. p += 3;
  51235. }
  51236. };
  51237. instance.updateMeshPositions(positionFunction, false);
  51238. return instance;
  51239. }
  51240. // dashed lines creation
  51241. var dashedLines = new BABYLON.LinesMesh(name, scene);
  51242. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  51243. vertexData.applyToMesh(dashedLines, options.updatable);
  51244. dashedLines.dashSize = dashSize;
  51245. dashedLines.gapSize = gapSize;
  51246. return dashedLines;
  51247. };
  51248. /**
  51249. * Creates an extruded shape mesh.
  51250. * 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.
  51251. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  51252. *
  51253. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51254. * 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
  51255. * extruded along the Z axis.
  51256. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51257. * 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.
  51258. * The parameter `scale` (float, default 1) is the value to scale the shape.
  51259. * 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
  51260. * 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
  51261. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51262. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51263. * 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).
  51264. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51265. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51267. */
  51268. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  51269. if (scene === void 0) { scene = null; }
  51270. var path = options.path;
  51271. var shape = options.shape;
  51272. var scale = options.scale || 1;
  51273. var rotation = options.rotation || 0;
  51274. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51275. var updatable = options.updatable;
  51276. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51277. var instance = options.instance || null;
  51278. var invertUV = options.invertUV || false;
  51279. 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);
  51280. };
  51281. /**
  51282. * Creates an custom extruded shape mesh.
  51283. * 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.
  51284. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  51285. *
  51286. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51287. * 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
  51288. * extruded along the Z axis.
  51289. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51290. * 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
  51291. * and the distance of this point from the begining of the path :
  51292. * ```javascript
  51293. * var rotationFunction = function(i, distance) {
  51294. * // do things
  51295. * return rotationValue; }
  51296. * ```
  51297. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  51298. * 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
  51299. * and the distance of this point from the begining of the path :
  51300. * ```javascript
  51301. * var scaleFunction = function(i, distance) {
  51302. * // do things
  51303. * return scaleValue;}
  51304. * ```
  51305. * It must returns a float value that will be the scale value applied to the shape on each path point.
  51306. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  51307. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  51308. * 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
  51309. * 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
  51310. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51312. * 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).
  51313. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51314. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51315. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51316. */
  51317. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  51318. var path = options.path;
  51319. var shape = options.shape;
  51320. var scaleFunction = options.scaleFunction || (function () { return 1; });
  51321. var rotationFunction = options.rotationFunction || (function () { return 0; });
  51322. var ribbonCloseArray = options.ribbonCloseArray || false;
  51323. var ribbonClosePath = options.ribbonClosePath || false;
  51324. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51325. var updatable = options.updatable;
  51326. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51327. var instance = options.instance;
  51328. var invertUV = options.invertUV || false;
  51329. 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);
  51330. };
  51331. /**
  51332. * Creates lathe mesh.
  51333. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  51334. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  51335. *
  51336. * 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
  51337. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  51338. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  51339. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  51340. * 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.
  51341. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  51342. * 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
  51343. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51344. * 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).
  51345. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51346. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51348. */
  51349. MeshBuilder.CreateLathe = function (name, options, scene) {
  51350. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  51351. var closed = (options.closed === undefined) ? true : options.closed;
  51352. var shape = options.shape;
  51353. var radius = options.radius || 1;
  51354. var tessellation = options.tessellation || 64;
  51355. var updatable = options.updatable;
  51356. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51357. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51358. var pi2 = Math.PI * 2;
  51359. var paths = new Array();
  51360. var invertUV = options.invertUV || false;
  51361. var i = 0;
  51362. var p = 0;
  51363. var step = pi2 / tessellation * arc;
  51364. var rotated;
  51365. var path = new Array();
  51366. ;
  51367. for (i = 0; i <= tessellation; i++) {
  51368. var path = [];
  51369. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  51370. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  51371. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  51372. }
  51373. for (p = 0; p < shape.length; p++) {
  51374. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  51375. path.push(rotated);
  51376. }
  51377. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  51378. 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));
  51379. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  51380. }
  51381. paths.push(path);
  51382. }
  51383. // lathe ribbon
  51384. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51385. return lathe;
  51386. };
  51387. /**
  51388. * Creates a plane mesh.
  51389. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51390. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  51391. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  51392. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  51393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51394. * 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).
  51395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51397. */
  51398. MeshBuilder.CreatePlane = function (name, options, scene) {
  51399. var plane = new BABYLON.Mesh(name, scene);
  51400. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51401. plane._originalBuilderSideOrientation = options.sideOrientation;
  51402. var vertexData = BABYLON.VertexData.CreatePlane(options);
  51403. vertexData.applyToMesh(plane, options.updatable);
  51404. if (options.sourcePlane) {
  51405. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  51406. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  51407. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  51408. plane.rotate(vectorProduct, product);
  51409. }
  51410. return plane;
  51411. };
  51412. /**
  51413. * Creates a ground mesh.
  51414. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51415. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  51416. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  51417. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51418. */
  51419. MeshBuilder.CreateGround = function (name, options, scene) {
  51420. var ground = new BABYLON.GroundMesh(name, scene);
  51421. ground._setReady(false);
  51422. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  51423. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  51424. ground._width = options.width || 1;
  51425. ground._height = options.height || 1;
  51426. ground._maxX = ground._width / 2;
  51427. ground._maxZ = ground._height / 2;
  51428. ground._minX = -ground._maxX;
  51429. ground._minZ = -ground._maxZ;
  51430. var vertexData = BABYLON.VertexData.CreateGround(options);
  51431. vertexData.applyToMesh(ground, options.updatable);
  51432. ground._setReady(true);
  51433. return ground;
  51434. };
  51435. /**
  51436. * Creates a tiled ground mesh.
  51437. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  51438. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  51439. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  51440. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  51441. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  51442. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  51443. * numbers of subdivisions on the ground width and height of each tile.
  51444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51445. */
  51446. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  51447. var tiledGround = new BABYLON.Mesh(name, scene);
  51448. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  51449. vertexData.applyToMesh(tiledGround, options.updatable);
  51450. return tiledGround;
  51451. };
  51452. /**
  51453. * Creates a ground mesh from a height map.
  51454. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  51455. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  51456. * The parameter `url` sets the URL of the height map image resource.
  51457. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  51458. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  51459. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  51460. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  51461. * 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.
  51462. * 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).
  51463. * This function is passed the newly built mesh :
  51464. * ```javascript
  51465. * function(mesh) { // do things
  51466. * return; }
  51467. * ```
  51468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51469. */
  51470. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  51471. var width = options.width || 10.0;
  51472. var height = options.height || 10.0;
  51473. var subdivisions = options.subdivisions || 1 | 0;
  51474. var minHeight = options.minHeight || 0.0;
  51475. var maxHeight = options.maxHeight || 1.0;
  51476. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  51477. var updatable = options.updatable;
  51478. var onReady = options.onReady;
  51479. var ground = new BABYLON.GroundMesh(name, scene);
  51480. ground._subdivisionsX = subdivisions;
  51481. ground._subdivisionsY = subdivisions;
  51482. ground._width = width;
  51483. ground._height = height;
  51484. ground._maxX = ground._width / 2.0;
  51485. ground._maxZ = ground._height / 2.0;
  51486. ground._minX = -ground._maxX;
  51487. ground._minZ = -ground._maxZ;
  51488. ground._setReady(false);
  51489. var onload = function (img) {
  51490. // Getting height map data
  51491. var canvas = document.createElement("canvas");
  51492. var context = canvas.getContext("2d");
  51493. if (!context) {
  51494. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  51495. }
  51496. if (scene.isDisposed) {
  51497. return;
  51498. }
  51499. var bufferWidth = img.width;
  51500. var bufferHeight = img.height;
  51501. canvas.width = bufferWidth;
  51502. canvas.height = bufferHeight;
  51503. context.drawImage(img, 0, 0);
  51504. // Create VertexData from map data
  51505. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  51506. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  51507. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  51508. width: width, height: height,
  51509. subdivisions: subdivisions,
  51510. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  51511. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  51512. });
  51513. vertexData.applyToMesh(ground, updatable);
  51514. ground._setReady(true);
  51515. //execute ready callback, if set
  51516. if (onReady) {
  51517. onReady(ground);
  51518. }
  51519. };
  51520. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  51521. return ground;
  51522. };
  51523. /**
  51524. * Creates a polygon mesh.
  51525. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  51526. * 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.
  51527. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51528. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51529. * 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).
  51530. * Remember you can only change the shape positions, not their number when updating a polygon.
  51531. */
  51532. MeshBuilder.CreatePolygon = function (name, options, scene) {
  51533. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51534. var shape = options.shape;
  51535. var holes = options.holes || [];
  51536. var depth = options.depth || 0;
  51537. var contours = [];
  51538. var hole = [];
  51539. for (var i = 0; i < shape.length; i++) {
  51540. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  51541. }
  51542. var epsilon = 0.00000001;
  51543. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  51544. contours.pop();
  51545. }
  51546. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  51547. for (var hNb = 0; hNb < holes.length; hNb++) {
  51548. hole = [];
  51549. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  51550. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  51551. }
  51552. polygonTriangulation.addHole(hole);
  51553. }
  51554. var polygon = polygonTriangulation.build(options.updatable, depth);
  51555. polygon._originalBuilderSideOrientation = options.sideOrientation;
  51556. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  51557. vertexData.applyToMesh(polygon, options.updatable);
  51558. return polygon;
  51559. };
  51560. ;
  51561. /**
  51562. * Creates an extruded polygon mesh, with depth in the Y direction.
  51563. * 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).
  51564. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51565. */
  51566. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  51567. return MeshBuilder.CreatePolygon(name, options, scene);
  51568. };
  51569. ;
  51570. /**
  51571. * Creates a tube mesh.
  51572. * 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.
  51573. *
  51574. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  51575. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  51576. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  51577. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  51578. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  51579. * 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.
  51580. * It must return a radius value (positive float) :
  51581. * ```javascript
  51582. * var radiusFunction = function(i, distance) {
  51583. * // do things
  51584. * return radius; }
  51585. * ```
  51586. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  51587. * 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
  51588. * 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
  51589. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51590. * 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).
  51591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51592. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51594. */
  51595. MeshBuilder.CreateTube = function (name, options, scene) {
  51596. var path = options.path;
  51597. var instance = options.instance;
  51598. var radius = 1.0;
  51599. if (instance) {
  51600. radius = instance.radius;
  51601. }
  51602. if (options.radius !== undefined) {
  51603. radius = options.radius;
  51604. }
  51605. ;
  51606. var tessellation = options.tessellation || 64 | 0;
  51607. var radiusFunction = options.radiusFunction || null;
  51608. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51609. var invertUV = options.invertUV || false;
  51610. var updatable = options.updatable;
  51611. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51612. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  51613. // tube geometry
  51614. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  51615. var tangents = path3D.getTangents();
  51616. var normals = path3D.getNormals();
  51617. var distances = path3D.getDistances();
  51618. var pi2 = Math.PI * 2;
  51619. var step = pi2 / tessellation * arc;
  51620. var returnRadius = function () { return radius; };
  51621. var radiusFunctionFinal = radiusFunction || returnRadius;
  51622. var circlePath;
  51623. var rad;
  51624. var normal;
  51625. var rotated;
  51626. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  51627. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  51628. for (var i = 0; i < path.length; i++) {
  51629. rad = radiusFunctionFinal(i, distances[i]); // current radius
  51630. circlePath = Array(); // current circle array
  51631. normal = normals[i]; // current normal
  51632. for (var t = 0; t < tessellation; t++) {
  51633. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  51634. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  51635. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  51636. rotated.scaleInPlace(rad).addInPlace(path[i]);
  51637. circlePath[t] = rotated;
  51638. }
  51639. circlePaths[index] = circlePath;
  51640. index++;
  51641. }
  51642. // cap
  51643. var capPath = function (nbPoints, pathIndex) {
  51644. var pointCap = Array();
  51645. for (var i = 0; i < nbPoints; i++) {
  51646. pointCap.push(path[pathIndex]);
  51647. }
  51648. return pointCap;
  51649. };
  51650. switch (cap) {
  51651. case BABYLON.Mesh.NO_CAP:
  51652. break;
  51653. case BABYLON.Mesh.CAP_START:
  51654. circlePaths[0] = capPath(tessellation, 0);
  51655. circlePaths[1] = circlePaths[2].slice(0);
  51656. break;
  51657. case BABYLON.Mesh.CAP_END:
  51658. circlePaths[index] = circlePaths[index - 1].slice(0);
  51659. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51660. break;
  51661. case BABYLON.Mesh.CAP_ALL:
  51662. circlePaths[0] = capPath(tessellation, 0);
  51663. circlePaths[1] = circlePaths[2].slice(0);
  51664. circlePaths[index] = circlePaths[index - 1].slice(0);
  51665. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  51666. break;
  51667. default:
  51668. break;
  51669. }
  51670. return circlePaths;
  51671. };
  51672. var path3D;
  51673. var pathArray;
  51674. if (instance) {
  51675. var arc = options.arc || instance.arc;
  51676. path3D = (instance.path3D).update(path);
  51677. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  51678. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  51679. instance.path3D = path3D;
  51680. instance.pathArray = pathArray;
  51681. instance.arc = arc;
  51682. instance.radius = radius;
  51683. return instance;
  51684. }
  51685. // tube creation
  51686. path3D = new BABYLON.Path3D(path);
  51687. var newPathArray = new Array();
  51688. cap = (cap < 0 || cap > 3) ? 0 : cap;
  51689. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  51690. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51691. tube.pathArray = pathArray;
  51692. tube.path3D = path3D;
  51693. tube.tessellation = tessellation;
  51694. tube.cap = cap;
  51695. tube.arc = options.arc;
  51696. tube.radius = radius;
  51697. return tube;
  51698. };
  51699. /**
  51700. * Creates a polyhedron mesh.
  51701. *
  51702. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  51703. * 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
  51704. * to choose the wanted type.
  51705. * The parameter `size` (positive float, default 1) sets the polygon size.
  51706. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  51707. * 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`.
  51708. * 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
  51709. * 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)`).
  51710. * 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
  51711. * 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.
  51712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51713. * 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).
  51714. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51715. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51716. */
  51717. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  51718. var polyhedron = new BABYLON.Mesh(name, scene);
  51719. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51720. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  51721. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  51722. vertexData.applyToMesh(polyhedron, options.updatable);
  51723. return polyhedron;
  51724. };
  51725. /**
  51726. * Creates a decal mesh.
  51727. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  51728. * 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.
  51729. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  51730. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  51731. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  51732. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  51733. */
  51734. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  51735. var indices = sourceMesh.getIndices();
  51736. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51737. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51738. var position = options.position || BABYLON.Vector3.Zero();
  51739. var normal = options.normal || BABYLON.Vector3.Up();
  51740. var size = options.size || BABYLON.Vector3.One();
  51741. var angle = options.angle || 0;
  51742. // Getting correct rotation
  51743. if (!normal) {
  51744. var target = new BABYLON.Vector3(0, 0, 1);
  51745. var camera = sourceMesh.getScene().activeCamera;
  51746. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  51747. normal = camera.globalPosition.subtract(cameraWorldTarget);
  51748. }
  51749. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  51750. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  51751. var pitch = Math.atan2(normal.y, len);
  51752. // Matrix
  51753. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  51754. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  51755. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  51756. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  51757. var vertexData = new BABYLON.VertexData();
  51758. vertexData.indices = [];
  51759. vertexData.positions = [];
  51760. vertexData.normals = [];
  51761. vertexData.uvs = [];
  51762. var currentVertexDataIndex = 0;
  51763. var extractDecalVector3 = function (indexId) {
  51764. var result = new BABYLON.PositionNormalVertex();
  51765. if (!indices || !positions || !normals) {
  51766. return result;
  51767. }
  51768. var vertexId = indices[indexId];
  51769. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  51770. // Send vector to decal local world
  51771. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  51772. // Get normal
  51773. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  51774. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  51775. return result;
  51776. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  51777. var clip = function (vertices, axis) {
  51778. if (vertices.length === 0) {
  51779. return vertices;
  51780. }
  51781. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  51782. var clipVertices = function (v0, v1) {
  51783. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  51784. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  51785. };
  51786. var result = new Array();
  51787. for (var index = 0; index < vertices.length; index += 3) {
  51788. var v1Out;
  51789. var v2Out;
  51790. var v3Out;
  51791. var total = 0;
  51792. var nV1 = null;
  51793. var nV2 = null;
  51794. var nV3 = null;
  51795. var nV4 = null;
  51796. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  51797. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  51798. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  51799. v1Out = d1 > 0;
  51800. v2Out = d2 > 0;
  51801. v3Out = d3 > 0;
  51802. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  51803. switch (total) {
  51804. case 0:
  51805. result.push(vertices[index]);
  51806. result.push(vertices[index + 1]);
  51807. result.push(vertices[index + 2]);
  51808. break;
  51809. case 1:
  51810. if (v1Out) {
  51811. nV1 = vertices[index + 1];
  51812. nV2 = vertices[index + 2];
  51813. nV3 = clipVertices(vertices[index], nV1);
  51814. nV4 = clipVertices(vertices[index], nV2);
  51815. }
  51816. if (v2Out) {
  51817. nV1 = vertices[index];
  51818. nV2 = vertices[index + 2];
  51819. nV3 = clipVertices(vertices[index + 1], nV1);
  51820. nV4 = clipVertices(vertices[index + 1], nV2);
  51821. result.push(nV3);
  51822. result.push(nV2.clone());
  51823. result.push(nV1.clone());
  51824. result.push(nV2.clone());
  51825. result.push(nV3.clone());
  51826. result.push(nV4);
  51827. break;
  51828. }
  51829. if (v3Out) {
  51830. nV1 = vertices[index];
  51831. nV2 = vertices[index + 1];
  51832. nV3 = clipVertices(vertices[index + 2], nV1);
  51833. nV4 = clipVertices(vertices[index + 2], nV2);
  51834. }
  51835. if (nV1 && nV2 && nV3 && nV4) {
  51836. result.push(nV1.clone());
  51837. result.push(nV2.clone());
  51838. result.push(nV3);
  51839. result.push(nV4);
  51840. result.push(nV3.clone());
  51841. result.push(nV2.clone());
  51842. }
  51843. break;
  51844. case 2:
  51845. if (!v1Out) {
  51846. nV1 = vertices[index].clone();
  51847. nV2 = clipVertices(nV1, vertices[index + 1]);
  51848. nV3 = clipVertices(nV1, vertices[index + 2]);
  51849. result.push(nV1);
  51850. result.push(nV2);
  51851. result.push(nV3);
  51852. }
  51853. if (!v2Out) {
  51854. nV1 = vertices[index + 1].clone();
  51855. nV2 = clipVertices(nV1, vertices[index + 2]);
  51856. nV3 = clipVertices(nV1, vertices[index]);
  51857. result.push(nV1);
  51858. result.push(nV2);
  51859. result.push(nV3);
  51860. }
  51861. if (!v3Out) {
  51862. nV1 = vertices[index + 2].clone();
  51863. nV2 = clipVertices(nV1, vertices[index]);
  51864. nV3 = clipVertices(nV1, vertices[index + 1]);
  51865. result.push(nV1);
  51866. result.push(nV2);
  51867. result.push(nV3);
  51868. }
  51869. break;
  51870. case 3:
  51871. break;
  51872. }
  51873. }
  51874. return result;
  51875. };
  51876. for (var index = 0; index < indices.length; index += 3) {
  51877. var faceVertices = new Array();
  51878. faceVertices.push(extractDecalVector3(index));
  51879. faceVertices.push(extractDecalVector3(index + 1));
  51880. faceVertices.push(extractDecalVector3(index + 2));
  51881. // Clip
  51882. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  51883. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  51884. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  51885. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  51886. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  51887. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  51888. if (faceVertices.length === 0) {
  51889. continue;
  51890. }
  51891. // Add UVs and get back to world
  51892. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  51893. var vertex = faceVertices[vIndex];
  51894. //TODO check for Int32Array | Uint32Array | Uint16Array
  51895. vertexData.indices.push(currentVertexDataIndex);
  51896. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  51897. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  51898. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  51899. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  51900. currentVertexDataIndex++;
  51901. }
  51902. }
  51903. // Return mesh
  51904. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  51905. vertexData.applyToMesh(decal);
  51906. decal.position = position.clone();
  51907. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  51908. return decal;
  51909. };
  51910. // Privates
  51911. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  51912. // extrusion geometry
  51913. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  51914. var tangents = path3D.getTangents();
  51915. var normals = path3D.getNormals();
  51916. var binormals = path3D.getBinormals();
  51917. var distances = path3D.getDistances();
  51918. var angle = 0;
  51919. var returnScale = function () { return scale !== null ? scale : 1; };
  51920. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  51921. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  51922. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  51923. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  51924. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  51925. for (var i = 0; i < curve.length; i++) {
  51926. var shapePath = new Array();
  51927. var angleStep = rotate(i, distances[i]);
  51928. var scaleRatio = scl(i, distances[i]);
  51929. for (var p = 0; p < shape.length; p++) {
  51930. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  51931. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  51932. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  51933. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  51934. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  51935. shapePath[p] = rotated;
  51936. }
  51937. shapePaths[index] = shapePath;
  51938. angle += angleStep;
  51939. index++;
  51940. }
  51941. // cap
  51942. var capPath = function (shapePath) {
  51943. var pointCap = Array();
  51944. var barycenter = BABYLON.Vector3.Zero();
  51945. var i;
  51946. for (i = 0; i < shapePath.length; i++) {
  51947. barycenter.addInPlace(shapePath[i]);
  51948. }
  51949. barycenter.scaleInPlace(1.0 / shapePath.length);
  51950. for (i = 0; i < shapePath.length; i++) {
  51951. pointCap.push(barycenter);
  51952. }
  51953. return pointCap;
  51954. };
  51955. switch (cap) {
  51956. case BABYLON.Mesh.NO_CAP:
  51957. break;
  51958. case BABYLON.Mesh.CAP_START:
  51959. shapePaths[0] = capPath(shapePaths[2]);
  51960. shapePaths[1] = shapePaths[2];
  51961. break;
  51962. case BABYLON.Mesh.CAP_END:
  51963. shapePaths[index] = shapePaths[index - 1];
  51964. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  51965. break;
  51966. case BABYLON.Mesh.CAP_ALL:
  51967. shapePaths[0] = capPath(shapePaths[2]);
  51968. shapePaths[1] = shapePaths[2];
  51969. shapePaths[index] = shapePaths[index - 1];
  51970. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  51971. break;
  51972. default:
  51973. break;
  51974. }
  51975. return shapePaths;
  51976. };
  51977. var path3D;
  51978. var pathArray;
  51979. if (instance) {
  51980. path3D = (instance.path3D).update(curve);
  51981. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  51982. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  51983. return instance;
  51984. }
  51985. // extruded shape creation
  51986. path3D = new BABYLON.Path3D(curve);
  51987. var newShapePaths = new Array();
  51988. cap = (cap < 0 || cap > 3) ? 0 : cap;
  51989. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  51990. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  51991. extrudedGeneric.pathArray = pathArray;
  51992. extrudedGeneric.path3D = path3D;
  51993. extrudedGeneric.cap = cap;
  51994. return extrudedGeneric;
  51995. };
  51996. return MeshBuilder;
  51997. }());
  51998. BABYLON.MeshBuilder = MeshBuilder;
  51999. })(BABYLON || (BABYLON = {}));
  52000. //# sourceMappingURL=babylon.meshBuilder.js.map
  52001. var BABYLON;
  52002. (function (BABYLON) {
  52003. var AudioEngine = /** @class */ (function () {
  52004. function AudioEngine() {
  52005. this._audioContext = null;
  52006. this._audioContextInitialized = false;
  52007. this.canUseWebAudio = false;
  52008. this.WarnedWebAudioUnsupported = false;
  52009. this.unlocked = false;
  52010. this.isMP3supported = false;
  52011. this.isOGGsupported = false;
  52012. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52013. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52014. this.canUseWebAudio = true;
  52015. }
  52016. var audioElem = document.createElement('audio');
  52017. try {
  52018. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52019. this.isMP3supported = true;
  52020. }
  52021. }
  52022. catch (e) {
  52023. // protect error during capability check.
  52024. }
  52025. try {
  52026. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52027. this.isOGGsupported = true;
  52028. }
  52029. }
  52030. catch (e) {
  52031. // protect error during capability check.
  52032. }
  52033. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52034. this._unlockiOSaudio();
  52035. }
  52036. else {
  52037. this.unlocked = true;
  52038. }
  52039. }
  52040. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52041. get: function () {
  52042. if (!this._audioContextInitialized) {
  52043. this._initializeAudioContext();
  52044. }
  52045. return this._audioContext;
  52046. },
  52047. enumerable: true,
  52048. configurable: true
  52049. });
  52050. AudioEngine.prototype._unlockiOSaudio = function () {
  52051. var _this = this;
  52052. var unlockaudio = function () {
  52053. if (!_this.audioContext) {
  52054. return;
  52055. }
  52056. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52057. var source = _this.audioContext.createBufferSource();
  52058. source.buffer = buffer;
  52059. source.connect(_this.audioContext.destination);
  52060. source.start(0);
  52061. setTimeout(function () {
  52062. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52063. _this.unlocked = true;
  52064. window.removeEventListener('touchend', unlockaudio, false);
  52065. if (_this.onAudioUnlocked) {
  52066. _this.onAudioUnlocked();
  52067. }
  52068. }
  52069. }, 0);
  52070. };
  52071. window.addEventListener('touchend', unlockaudio, false);
  52072. };
  52073. AudioEngine.prototype._initializeAudioContext = function () {
  52074. try {
  52075. if (this.canUseWebAudio) {
  52076. this._audioContext = new AudioContext();
  52077. // create a global volume gain node
  52078. this.masterGain = this._audioContext.createGain();
  52079. this.masterGain.gain.value = 1;
  52080. this.masterGain.connect(this._audioContext.destination);
  52081. this._audioContextInitialized = true;
  52082. }
  52083. }
  52084. catch (e) {
  52085. this.canUseWebAudio = false;
  52086. BABYLON.Tools.Error("Web Audio: " + e.message);
  52087. }
  52088. };
  52089. AudioEngine.prototype.dispose = function () {
  52090. if (this.canUseWebAudio && this._audioContextInitialized) {
  52091. if (this._connectedAnalyser && this._audioContext) {
  52092. this._connectedAnalyser.stopDebugCanvas();
  52093. this._connectedAnalyser.dispose();
  52094. this.masterGain.disconnect();
  52095. this.masterGain.connect(this._audioContext.destination);
  52096. this._connectedAnalyser = null;
  52097. }
  52098. this.masterGain.gain.value = 1;
  52099. }
  52100. this.WarnedWebAudioUnsupported = false;
  52101. };
  52102. AudioEngine.prototype.getGlobalVolume = function () {
  52103. if (this.canUseWebAudio && this._audioContextInitialized) {
  52104. return this.masterGain.gain.value;
  52105. }
  52106. else {
  52107. return -1;
  52108. }
  52109. };
  52110. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52111. if (this.canUseWebAudio && this._audioContextInitialized) {
  52112. this.masterGain.gain.value = newVolume;
  52113. }
  52114. };
  52115. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52116. if (this._connectedAnalyser) {
  52117. this._connectedAnalyser.stopDebugCanvas();
  52118. }
  52119. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52120. this._connectedAnalyser = analyser;
  52121. this.masterGain.disconnect();
  52122. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52123. }
  52124. };
  52125. return AudioEngine;
  52126. }());
  52127. BABYLON.AudioEngine = AudioEngine;
  52128. })(BABYLON || (BABYLON = {}));
  52129. //# sourceMappingURL=babylon.audioEngine.js.map
  52130. var BABYLON;
  52131. (function (BABYLON) {
  52132. var Sound = /** @class */ (function () {
  52133. /**
  52134. * Create a sound and attach it to a scene
  52135. * @param name Name of your sound
  52136. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52137. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52138. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52139. */
  52140. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52141. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52142. var _this = this;
  52143. this.autoplay = false;
  52144. this.loop = false;
  52145. this.useCustomAttenuation = false;
  52146. this.spatialSound = false;
  52147. this.refDistance = 1;
  52148. this.rolloffFactor = 1;
  52149. this.maxDistance = 100;
  52150. this.distanceModel = "linear";
  52151. this._panningModel = "equalpower";
  52152. this._playbackRate = 1;
  52153. this._streaming = false;
  52154. this._startTime = 0;
  52155. this._startOffset = 0;
  52156. this._position = BABYLON.Vector3.Zero();
  52157. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52158. this._volume = 1;
  52159. this._isReadyToPlay = false;
  52160. this.isPlaying = false;
  52161. this.isPaused = false;
  52162. this._isDirectional = false;
  52163. // Used if you'd like to create a directional sound.
  52164. // If not set, the sound will be omnidirectional
  52165. this._coneInnerAngle = 360;
  52166. this._coneOuterAngle = 360;
  52167. this._coneOuterGain = 0;
  52168. this._isOutputConnected = false;
  52169. this._urlType = "Unknown";
  52170. this.name = name;
  52171. this._scene = scene;
  52172. this._readyToPlayCallback = readyToPlayCallback;
  52173. // Default custom attenuation function is a linear attenuation
  52174. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52175. if (currentDistance < maxDistance) {
  52176. return currentVolume * (1 - currentDistance / maxDistance);
  52177. }
  52178. else {
  52179. return 0;
  52180. }
  52181. };
  52182. if (options) {
  52183. this.autoplay = options.autoplay || false;
  52184. this.loop = options.loop || false;
  52185. // if volume === 0, we need another way to check this option
  52186. if (options.volume !== undefined) {
  52187. this._volume = options.volume;
  52188. }
  52189. this.spatialSound = options.spatialSound || false;
  52190. this.maxDistance = options.maxDistance || 100;
  52191. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52192. this.rolloffFactor = options.rolloffFactor || 1;
  52193. this.refDistance = options.refDistance || 1;
  52194. this.distanceModel = options.distanceModel || "linear";
  52195. this._playbackRate = options.playbackRate || 1;
  52196. this._streaming = options.streaming || false;
  52197. }
  52198. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52199. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52200. this._soundGain.gain.value = this._volume;
  52201. this._inputAudioNode = this._soundGain;
  52202. this._ouputAudioNode = this._soundGain;
  52203. if (this.spatialSound) {
  52204. this._createSpatialParameters();
  52205. }
  52206. this._scene.mainSoundTrack.AddSound(this);
  52207. var validParameter = true;
  52208. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52209. if (urlOrArrayBuffer) {
  52210. if (typeof (urlOrArrayBuffer) === "string")
  52211. this._urlType = "String";
  52212. if (Array.isArray(urlOrArrayBuffer))
  52213. this._urlType = "Array";
  52214. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52215. this._urlType = "ArrayBuffer";
  52216. var urls = [];
  52217. var codecSupportedFound = false;
  52218. switch (this._urlType) {
  52219. case "ArrayBuffer":
  52220. if (urlOrArrayBuffer.byteLength > 0) {
  52221. codecSupportedFound = true;
  52222. this._soundLoaded(urlOrArrayBuffer);
  52223. }
  52224. break;
  52225. case "String":
  52226. urls.push(urlOrArrayBuffer);
  52227. case "Array":
  52228. if (urls.length === 0)
  52229. urls = urlOrArrayBuffer;
  52230. // If we found a supported format, we load it immediately and stop the loop
  52231. for (var i = 0; i < urls.length; i++) {
  52232. var url = urls[i];
  52233. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  52234. codecSupportedFound = true;
  52235. }
  52236. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  52237. codecSupportedFound = true;
  52238. }
  52239. if (url.indexOf(".wav", url.length - 4) !== -1) {
  52240. codecSupportedFound = true;
  52241. }
  52242. if (url.indexOf("blob:") !== -1) {
  52243. codecSupportedFound = true;
  52244. }
  52245. if (codecSupportedFound) {
  52246. // Loading sound using XHR2
  52247. if (!this._streaming) {
  52248. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  52249. }
  52250. else {
  52251. this._htmlAudioElement = new Audio(url);
  52252. this._htmlAudioElement.controls = false;
  52253. this._htmlAudioElement.loop = this.loop;
  52254. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  52255. this._htmlAudioElement.preload = "auto";
  52256. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  52257. _this._isReadyToPlay = true;
  52258. if (_this.autoplay) {
  52259. _this.play();
  52260. }
  52261. if (_this._readyToPlayCallback) {
  52262. _this._readyToPlayCallback();
  52263. }
  52264. });
  52265. document.body.appendChild(this._htmlAudioElement);
  52266. }
  52267. break;
  52268. }
  52269. }
  52270. break;
  52271. default:
  52272. validParameter = false;
  52273. break;
  52274. }
  52275. if (!validParameter) {
  52276. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  52277. }
  52278. else {
  52279. if (!codecSupportedFound) {
  52280. this._isReadyToPlay = true;
  52281. // Simulating a ready to play event to avoid breaking code path
  52282. if (this._readyToPlayCallback) {
  52283. window.setTimeout(function () {
  52284. if (_this._readyToPlayCallback) {
  52285. _this._readyToPlayCallback();
  52286. }
  52287. }, 1000);
  52288. }
  52289. }
  52290. }
  52291. }
  52292. }
  52293. else {
  52294. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  52295. this._scene.mainSoundTrack.AddSound(this);
  52296. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  52297. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  52298. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  52299. }
  52300. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  52301. if (this._readyToPlayCallback) {
  52302. window.setTimeout(function () {
  52303. if (_this._readyToPlayCallback) {
  52304. _this._readyToPlayCallback();
  52305. }
  52306. }, 1000);
  52307. }
  52308. }
  52309. }
  52310. Sound.prototype.dispose = function () {
  52311. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  52312. if (this.isPlaying) {
  52313. this.stop();
  52314. }
  52315. this._isReadyToPlay = false;
  52316. if (this.soundTrackId === -1) {
  52317. this._scene.mainSoundTrack.RemoveSound(this);
  52318. }
  52319. else {
  52320. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  52321. }
  52322. if (this._soundGain) {
  52323. this._soundGain.disconnect();
  52324. this._soundGain = null;
  52325. }
  52326. if (this._soundPanner) {
  52327. this._soundPanner.disconnect();
  52328. this._soundPanner = null;
  52329. }
  52330. if (this._soundSource) {
  52331. this._soundSource.disconnect();
  52332. this._soundSource = null;
  52333. }
  52334. this._audioBuffer = null;
  52335. if (this._htmlAudioElement) {
  52336. this._htmlAudioElement.pause();
  52337. this._htmlAudioElement.src = "";
  52338. document.body.removeChild(this._htmlAudioElement);
  52339. }
  52340. if (this._connectedMesh && this._registerFunc) {
  52341. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52342. this._connectedMesh = null;
  52343. }
  52344. }
  52345. };
  52346. Sound.prototype.isReady = function () {
  52347. return this._isReadyToPlay;
  52348. };
  52349. Sound.prototype._soundLoaded = function (audioData) {
  52350. var _this = this;
  52351. if (!BABYLON.Engine.audioEngine.audioContext) {
  52352. return;
  52353. }
  52354. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  52355. _this._audioBuffer = buffer;
  52356. _this._isReadyToPlay = true;
  52357. if (_this.autoplay) {
  52358. _this.play();
  52359. }
  52360. if (_this._readyToPlayCallback) {
  52361. _this._readyToPlayCallback();
  52362. }
  52363. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  52364. };
  52365. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  52366. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52367. this._audioBuffer = audioBuffer;
  52368. this._isReadyToPlay = true;
  52369. }
  52370. };
  52371. Sound.prototype.updateOptions = function (options) {
  52372. if (options) {
  52373. this.loop = options.loop || this.loop;
  52374. this.maxDistance = options.maxDistance || this.maxDistance;
  52375. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  52376. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  52377. this.refDistance = options.refDistance || this.refDistance;
  52378. this.distanceModel = options.distanceModel || this.distanceModel;
  52379. this._playbackRate = options.playbackRate || this._playbackRate;
  52380. this._updateSpatialParameters();
  52381. if (this.isPlaying) {
  52382. if (this._streaming) {
  52383. this._htmlAudioElement.playbackRate = this._playbackRate;
  52384. }
  52385. else {
  52386. if (this._soundSource) {
  52387. this._soundSource.playbackRate.value = this._playbackRate;
  52388. }
  52389. }
  52390. }
  52391. }
  52392. };
  52393. Sound.prototype._createSpatialParameters = function () {
  52394. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52395. if (this._scene.headphone) {
  52396. this._panningModel = "HRTF";
  52397. }
  52398. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  52399. this._updateSpatialParameters();
  52400. this._soundPanner.connect(this._ouputAudioNode);
  52401. this._inputAudioNode = this._soundPanner;
  52402. }
  52403. };
  52404. Sound.prototype._updateSpatialParameters = function () {
  52405. if (this.spatialSound && this._soundPanner) {
  52406. if (this.useCustomAttenuation) {
  52407. // Tricks to disable in a way embedded Web Audio attenuation
  52408. this._soundPanner.distanceModel = "linear";
  52409. this._soundPanner.maxDistance = Number.MAX_VALUE;
  52410. this._soundPanner.refDistance = 1;
  52411. this._soundPanner.rolloffFactor = 1;
  52412. this._soundPanner.panningModel = this._panningModel;
  52413. }
  52414. else {
  52415. this._soundPanner.distanceModel = this.distanceModel;
  52416. this._soundPanner.maxDistance = this.maxDistance;
  52417. this._soundPanner.refDistance = this.refDistance;
  52418. this._soundPanner.rolloffFactor = this.rolloffFactor;
  52419. this._soundPanner.panningModel = this._panningModel;
  52420. }
  52421. }
  52422. };
  52423. Sound.prototype.switchPanningModelToHRTF = function () {
  52424. this._panningModel = "HRTF";
  52425. this._switchPanningModel();
  52426. };
  52427. Sound.prototype.switchPanningModelToEqualPower = function () {
  52428. this._panningModel = "equalpower";
  52429. this._switchPanningModel();
  52430. };
  52431. Sound.prototype._switchPanningModel = function () {
  52432. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52433. this._soundPanner.panningModel = this._panningModel;
  52434. }
  52435. };
  52436. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  52437. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52438. if (this._isOutputConnected) {
  52439. this._ouputAudioNode.disconnect();
  52440. }
  52441. this._ouputAudioNode.connect(soundTrackAudioNode);
  52442. this._isOutputConnected = true;
  52443. }
  52444. };
  52445. /**
  52446. * Transform this sound into a directional source
  52447. * @param coneInnerAngle Size of the inner cone in degree
  52448. * @param coneOuterAngle Size of the outer cone in degree
  52449. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  52450. */
  52451. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  52452. if (coneOuterAngle < coneInnerAngle) {
  52453. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  52454. return;
  52455. }
  52456. this._coneInnerAngle = coneInnerAngle;
  52457. this._coneOuterAngle = coneOuterAngle;
  52458. this._coneOuterGain = coneOuterGain;
  52459. this._isDirectional = true;
  52460. if (this.isPlaying && this.loop) {
  52461. this.stop();
  52462. this.play();
  52463. }
  52464. };
  52465. Sound.prototype.setPosition = function (newPosition) {
  52466. this._position = newPosition;
  52467. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52468. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52469. }
  52470. };
  52471. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  52472. this._localDirection = newLocalDirection;
  52473. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  52474. this._updateDirection();
  52475. }
  52476. };
  52477. Sound.prototype._updateDirection = function () {
  52478. if (!this._connectedMesh || !this._soundPanner) {
  52479. return;
  52480. }
  52481. var mat = this._connectedMesh.getWorldMatrix();
  52482. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  52483. direction.normalize();
  52484. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  52485. };
  52486. Sound.prototype.updateDistanceFromListener = function () {
  52487. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  52488. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  52489. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  52490. }
  52491. };
  52492. Sound.prototype.setAttenuationFunction = function (callback) {
  52493. this._customAttenuationFunction = callback;
  52494. };
  52495. /**
  52496. * Play the sound
  52497. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  52498. * @param offset (optional) Start the sound setting it at a specific time
  52499. */
  52500. Sound.prototype.play = function (time, offset) {
  52501. var _this = this;
  52502. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  52503. try {
  52504. if (this._startOffset < 0) {
  52505. time = -this._startOffset;
  52506. this._startOffset = 0;
  52507. }
  52508. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52509. if (!this._soundSource || !this._streamingSource) {
  52510. if (this.spatialSound && this._soundPanner) {
  52511. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52512. if (this._isDirectional) {
  52513. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  52514. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  52515. this._soundPanner.coneOuterGain = this._coneOuterGain;
  52516. if (this._connectedMesh) {
  52517. this._updateDirection();
  52518. }
  52519. else {
  52520. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  52521. }
  52522. }
  52523. }
  52524. }
  52525. if (this._streaming) {
  52526. if (!this._streamingSource) {
  52527. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  52528. this._htmlAudioElement.onended = function () { _this._onended(); };
  52529. this._htmlAudioElement.playbackRate = this._playbackRate;
  52530. }
  52531. this._streamingSource.disconnect();
  52532. this._streamingSource.connect(this._inputAudioNode);
  52533. this._htmlAudioElement.play();
  52534. }
  52535. else {
  52536. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  52537. this._soundSource.buffer = this._audioBuffer;
  52538. this._soundSource.connect(this._inputAudioNode);
  52539. this._soundSource.loop = this.loop;
  52540. this._soundSource.playbackRate.value = this._playbackRate;
  52541. this._soundSource.onended = function () { _this._onended(); };
  52542. if (this._soundSource.buffer) {
  52543. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  52544. }
  52545. }
  52546. this._startTime = startTime;
  52547. this.isPlaying = true;
  52548. this.isPaused = false;
  52549. }
  52550. catch (ex) {
  52551. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  52552. }
  52553. }
  52554. };
  52555. Sound.prototype._onended = function () {
  52556. this.isPlaying = false;
  52557. if (this.onended) {
  52558. this.onended();
  52559. }
  52560. };
  52561. /**
  52562. * Stop the sound
  52563. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  52564. */
  52565. Sound.prototype.stop = function (time) {
  52566. if (this.isPlaying) {
  52567. if (this._streaming) {
  52568. this._htmlAudioElement.pause();
  52569. // Test needed for Firefox or it will generate an Invalid State Error
  52570. if (this._htmlAudioElement.currentTime > 0) {
  52571. this._htmlAudioElement.currentTime = 0;
  52572. }
  52573. }
  52574. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  52575. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52576. this._soundSource.stop(stopTime);
  52577. this._soundSource.onended = function () { };
  52578. if (!this.isPaused) {
  52579. this._startOffset = 0;
  52580. }
  52581. }
  52582. this.isPlaying = false;
  52583. }
  52584. };
  52585. Sound.prototype.pause = function () {
  52586. if (this.isPlaying) {
  52587. this.isPaused = true;
  52588. if (this._streaming) {
  52589. this._htmlAudioElement.pause();
  52590. }
  52591. else if (BABYLON.Engine.audioEngine.audioContext) {
  52592. this.stop(0);
  52593. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  52594. }
  52595. }
  52596. };
  52597. Sound.prototype.setVolume = function (newVolume, time) {
  52598. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  52599. if (time && BABYLON.Engine.audioEngine.audioContext) {
  52600. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  52601. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  52602. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  52603. }
  52604. else {
  52605. this._soundGain.gain.value = newVolume;
  52606. }
  52607. }
  52608. this._volume = newVolume;
  52609. };
  52610. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  52611. this._playbackRate = newPlaybackRate;
  52612. if (this.isPlaying) {
  52613. if (this._streaming) {
  52614. this._htmlAudioElement.playbackRate = this._playbackRate;
  52615. }
  52616. else if (this._soundSource) {
  52617. this._soundSource.playbackRate.value = this._playbackRate;
  52618. }
  52619. }
  52620. };
  52621. Sound.prototype.getVolume = function () {
  52622. return this._volume;
  52623. };
  52624. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  52625. var _this = this;
  52626. if (this._connectedMesh && this._registerFunc) {
  52627. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52628. this._registerFunc = null;
  52629. }
  52630. this._connectedMesh = meshToConnectTo;
  52631. if (!this.spatialSound) {
  52632. this.spatialSound = true;
  52633. this._createSpatialParameters();
  52634. if (this.isPlaying && this.loop) {
  52635. this.stop();
  52636. this.play();
  52637. }
  52638. }
  52639. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  52640. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  52641. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  52642. };
  52643. Sound.prototype.detachFromMesh = function () {
  52644. if (this._connectedMesh && this._registerFunc) {
  52645. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52646. this._registerFunc = null;
  52647. this._connectedMesh = null;
  52648. }
  52649. };
  52650. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  52651. if (!node.getBoundingInfo) {
  52652. return;
  52653. }
  52654. var mesh = node;
  52655. var boundingInfo = mesh.getBoundingInfo();
  52656. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  52657. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  52658. this._updateDirection();
  52659. }
  52660. };
  52661. Sound.prototype.clone = function () {
  52662. var _this = this;
  52663. if (!this._streaming) {
  52664. var setBufferAndRun = function () {
  52665. if (_this._isReadyToPlay) {
  52666. clonedSound._audioBuffer = _this.getAudioBuffer();
  52667. clonedSound._isReadyToPlay = true;
  52668. if (clonedSound.autoplay) {
  52669. clonedSound.play();
  52670. }
  52671. }
  52672. else {
  52673. window.setTimeout(setBufferAndRun, 300);
  52674. }
  52675. };
  52676. var currentOptions = {
  52677. autoplay: this.autoplay, loop: this.loop,
  52678. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  52679. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  52680. refDistance: this.refDistance, distanceModel: this.distanceModel
  52681. };
  52682. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  52683. if (this.useCustomAttenuation) {
  52684. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  52685. }
  52686. clonedSound.setPosition(this._position);
  52687. clonedSound.setPlaybackRate(this._playbackRate);
  52688. setBufferAndRun();
  52689. return clonedSound;
  52690. }
  52691. else {
  52692. return null;
  52693. }
  52694. };
  52695. Sound.prototype.getAudioBuffer = function () {
  52696. return this._audioBuffer;
  52697. };
  52698. Sound.prototype.serialize = function () {
  52699. var serializationObject = {
  52700. name: this.name,
  52701. url: this.name,
  52702. autoplay: this.autoplay,
  52703. loop: this.loop,
  52704. volume: this._volume,
  52705. spatialSound: this.spatialSound,
  52706. maxDistance: this.maxDistance,
  52707. rolloffFactor: this.rolloffFactor,
  52708. refDistance: this.refDistance,
  52709. distanceModel: this.distanceModel,
  52710. playbackRate: this._playbackRate,
  52711. panningModel: this._panningModel,
  52712. soundTrackId: this.soundTrackId
  52713. };
  52714. if (this.spatialSound) {
  52715. if (this._connectedMesh)
  52716. serializationObject.connectedMeshId = this._connectedMesh.id;
  52717. serializationObject.position = this._position.asArray();
  52718. serializationObject.refDistance = this.refDistance;
  52719. serializationObject.distanceModel = this.distanceModel;
  52720. serializationObject.isDirectional = this._isDirectional;
  52721. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  52722. serializationObject.coneInnerAngle = this._coneInnerAngle;
  52723. serializationObject.coneOuterAngle = this._coneOuterAngle;
  52724. serializationObject.coneOuterGain = this._coneOuterGain;
  52725. }
  52726. return serializationObject;
  52727. };
  52728. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  52729. var soundName = parsedSound.name;
  52730. var soundUrl;
  52731. if (parsedSound.url) {
  52732. soundUrl = rootUrl + parsedSound.url;
  52733. }
  52734. else {
  52735. soundUrl = rootUrl + soundName;
  52736. }
  52737. var options = {
  52738. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  52739. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  52740. rolloffFactor: parsedSound.rolloffFactor,
  52741. refDistance: parsedSound.refDistance,
  52742. distanceModel: parsedSound.distanceModel,
  52743. playbackRate: parsedSound.playbackRate
  52744. };
  52745. var newSound;
  52746. if (!sourceSound) {
  52747. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  52748. scene._addPendingData(newSound);
  52749. }
  52750. else {
  52751. var setBufferAndRun = function () {
  52752. if (sourceSound._isReadyToPlay) {
  52753. newSound._audioBuffer = sourceSound.getAudioBuffer();
  52754. newSound._isReadyToPlay = true;
  52755. if (newSound.autoplay) {
  52756. newSound.play();
  52757. }
  52758. }
  52759. else {
  52760. window.setTimeout(setBufferAndRun, 300);
  52761. }
  52762. };
  52763. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  52764. setBufferAndRun();
  52765. }
  52766. if (parsedSound.position) {
  52767. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  52768. newSound.setPosition(soundPosition);
  52769. }
  52770. if (parsedSound.isDirectional) {
  52771. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  52772. if (parsedSound.localDirectionToMesh) {
  52773. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  52774. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  52775. }
  52776. }
  52777. if (parsedSound.connectedMeshId) {
  52778. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  52779. if (connectedMesh) {
  52780. newSound.attachToMesh(connectedMesh);
  52781. }
  52782. }
  52783. return newSound;
  52784. };
  52785. return Sound;
  52786. }());
  52787. BABYLON.Sound = Sound;
  52788. })(BABYLON || (BABYLON = {}));
  52789. //# sourceMappingURL=babylon.sound.js.map
  52790. var BABYLON;
  52791. (function (BABYLON) {
  52792. var SoundTrack = /** @class */ (function () {
  52793. function SoundTrack(scene, options) {
  52794. this.id = -1;
  52795. this._isMainTrack = false;
  52796. this._isInitialized = false;
  52797. this._scene = scene;
  52798. this.soundCollection = new Array();
  52799. this._options = options;
  52800. if (!this._isMainTrack) {
  52801. this._scene.soundTracks.push(this);
  52802. this.id = this._scene.soundTracks.length - 1;
  52803. }
  52804. }
  52805. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  52806. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52807. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  52808. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  52809. if (this._options) {
  52810. if (this._options.volume) {
  52811. this._outputAudioNode.gain.value = this._options.volume;
  52812. }
  52813. if (this._options.mainTrack) {
  52814. this._isMainTrack = this._options.mainTrack;
  52815. }
  52816. }
  52817. this._isInitialized = true;
  52818. }
  52819. };
  52820. SoundTrack.prototype.dispose = function () {
  52821. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52822. if (this._connectedAnalyser) {
  52823. this._connectedAnalyser.stopDebugCanvas();
  52824. }
  52825. while (this.soundCollection.length) {
  52826. this.soundCollection[0].dispose();
  52827. }
  52828. if (this._outputAudioNode) {
  52829. this._outputAudioNode.disconnect();
  52830. }
  52831. this._outputAudioNode = null;
  52832. }
  52833. };
  52834. SoundTrack.prototype.AddSound = function (sound) {
  52835. if (!this._isInitialized) {
  52836. this._initializeSoundTrackAudioGraph();
  52837. }
  52838. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52839. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  52840. }
  52841. if (sound.soundTrackId) {
  52842. if (sound.soundTrackId === -1) {
  52843. this._scene.mainSoundTrack.RemoveSound(sound);
  52844. }
  52845. else {
  52846. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  52847. }
  52848. }
  52849. this.soundCollection.push(sound);
  52850. sound.soundTrackId = this.id;
  52851. };
  52852. SoundTrack.prototype.RemoveSound = function (sound) {
  52853. var index = this.soundCollection.indexOf(sound);
  52854. if (index !== -1) {
  52855. this.soundCollection.splice(index, 1);
  52856. }
  52857. };
  52858. SoundTrack.prototype.setVolume = function (newVolume) {
  52859. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52860. this._outputAudioNode.gain.value = newVolume;
  52861. }
  52862. };
  52863. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  52864. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52865. for (var i = 0; i < this.soundCollection.length; i++) {
  52866. this.soundCollection[i].switchPanningModelToHRTF();
  52867. }
  52868. }
  52869. };
  52870. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  52871. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52872. for (var i = 0; i < this.soundCollection.length; i++) {
  52873. this.soundCollection[i].switchPanningModelToEqualPower();
  52874. }
  52875. }
  52876. };
  52877. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  52878. if (this._connectedAnalyser) {
  52879. this._connectedAnalyser.stopDebugCanvas();
  52880. }
  52881. this._connectedAnalyser = analyser;
  52882. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  52883. this._outputAudioNode.disconnect();
  52884. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  52885. }
  52886. };
  52887. return SoundTrack;
  52888. }());
  52889. BABYLON.SoundTrack = SoundTrack;
  52890. })(BABYLON || (BABYLON = {}));
  52891. //# sourceMappingURL=babylon.soundtrack.js.map
  52892. var BABYLON;
  52893. (function (BABYLON) {
  52894. var Analyser = /** @class */ (function () {
  52895. function Analyser(scene) {
  52896. this.SMOOTHING = 0.75;
  52897. this.FFT_SIZE = 512;
  52898. this.BARGRAPHAMPLITUDE = 256;
  52899. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  52900. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  52901. this._scene = scene;
  52902. this._audioEngine = BABYLON.Engine.audioEngine;
  52903. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  52904. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  52905. this._webAudioAnalyser.minDecibels = -140;
  52906. this._webAudioAnalyser.maxDecibels = 0;
  52907. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52908. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  52909. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  52910. }
  52911. }
  52912. Analyser.prototype.getFrequencyBinCount = function () {
  52913. if (this._audioEngine.canUseWebAudio) {
  52914. return this._webAudioAnalyser.frequencyBinCount;
  52915. }
  52916. else {
  52917. return 0;
  52918. }
  52919. };
  52920. Analyser.prototype.getByteFrequencyData = function () {
  52921. if (this._audioEngine.canUseWebAudio) {
  52922. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52923. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52924. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  52925. }
  52926. return this._byteFreqs;
  52927. };
  52928. Analyser.prototype.getByteTimeDomainData = function () {
  52929. if (this._audioEngine.canUseWebAudio) {
  52930. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52931. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52932. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  52933. }
  52934. return this._byteTime;
  52935. };
  52936. Analyser.prototype.getFloatFrequencyData = function () {
  52937. if (this._audioEngine.canUseWebAudio) {
  52938. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  52939. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  52940. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  52941. }
  52942. return this._floatFreqs;
  52943. };
  52944. Analyser.prototype.drawDebugCanvas = function () {
  52945. var _this = this;
  52946. if (this._audioEngine.canUseWebAudio) {
  52947. if (!this._debugCanvas) {
  52948. this._debugCanvas = document.createElement("canvas");
  52949. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  52950. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  52951. this._debugCanvas.style.position = "absolute";
  52952. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  52953. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  52954. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  52955. document.body.appendChild(this._debugCanvas);
  52956. this._registerFunc = function () {
  52957. _this.drawDebugCanvas();
  52958. };
  52959. this._scene.registerBeforeRender(this._registerFunc);
  52960. }
  52961. if (this._registerFunc && this._debugCanvasContext) {
  52962. var workingArray = this.getByteFrequencyData();
  52963. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  52964. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  52965. // Draw the frequency domain chart.
  52966. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  52967. var value = workingArray[i];
  52968. var percent = value / this.BARGRAPHAMPLITUDE;
  52969. var height = this.DEBUGCANVASSIZE.height * percent;
  52970. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  52971. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  52972. var hue = i / this.getFrequencyBinCount() * 360;
  52973. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  52974. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  52975. }
  52976. }
  52977. }
  52978. };
  52979. Analyser.prototype.stopDebugCanvas = function () {
  52980. if (this._debugCanvas) {
  52981. if (this._registerFunc) {
  52982. this._scene.unregisterBeforeRender(this._registerFunc);
  52983. this._registerFunc = null;
  52984. }
  52985. document.body.removeChild(this._debugCanvas);
  52986. this._debugCanvas = null;
  52987. this._debugCanvasContext = null;
  52988. }
  52989. };
  52990. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  52991. if (this._audioEngine.canUseWebAudio) {
  52992. inputAudioNode.connect(this._webAudioAnalyser);
  52993. this._webAudioAnalyser.connect(outputAudioNode);
  52994. }
  52995. };
  52996. Analyser.prototype.dispose = function () {
  52997. if (this._audioEngine.canUseWebAudio) {
  52998. this._webAudioAnalyser.disconnect();
  52999. }
  53000. };
  53001. return Analyser;
  53002. }());
  53003. BABYLON.Analyser = Analyser;
  53004. })(BABYLON || (BABYLON = {}));
  53005. //# sourceMappingURL=babylon.analyser.js.map
  53006. var BABYLON;
  53007. (function (BABYLON) {
  53008. var CubeTexture = /** @class */ (function (_super) {
  53009. __extends(CubeTexture, _super);
  53010. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53011. if (extensions === void 0) { extensions = null; }
  53012. if (noMipmap === void 0) { noMipmap = false; }
  53013. if (files === void 0) { files = null; }
  53014. if (onLoad === void 0) { onLoad = null; }
  53015. if (onError === void 0) { onError = null; }
  53016. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53017. if (prefiltered === void 0) { prefiltered = false; }
  53018. if (forcedExtension === void 0) { forcedExtension = null; }
  53019. var _this = _super.call(this, scene) || this;
  53020. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53021. _this.name = rootUrl;
  53022. _this.url = rootUrl;
  53023. _this._noMipmap = noMipmap;
  53024. _this.hasAlpha = false;
  53025. _this._format = format;
  53026. _this._prefiltered = prefiltered;
  53027. _this.isCube = true;
  53028. _this._textureMatrix = BABYLON.Matrix.Identity();
  53029. if (prefiltered) {
  53030. _this.gammaSpace = false;
  53031. }
  53032. if (!rootUrl && !files) {
  53033. return _this;
  53034. }
  53035. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53036. var lastDot = rootUrl.lastIndexOf(".");
  53037. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53038. var isDDS = (extension === ".dds");
  53039. if (!files) {
  53040. if (!isDDS && !extensions) {
  53041. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53042. }
  53043. files = [];
  53044. if (extensions) {
  53045. for (var index = 0; index < extensions.length; index++) {
  53046. files.push(rootUrl + extensions[index]);
  53047. }
  53048. }
  53049. }
  53050. _this._files = files;
  53051. if (!_this._texture) {
  53052. if (!scene.useDelayedTextureLoading) {
  53053. if (prefiltered) {
  53054. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53055. }
  53056. else {
  53057. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53058. }
  53059. }
  53060. else {
  53061. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53062. }
  53063. }
  53064. else if (onLoad) {
  53065. if (_this._texture.isReady) {
  53066. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53067. }
  53068. else {
  53069. _this._texture.onLoadedObservable.add(onLoad);
  53070. }
  53071. }
  53072. return _this;
  53073. }
  53074. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53075. return new CubeTexture("", scene, null, noMipmap, files);
  53076. };
  53077. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53078. if (forcedExtension === void 0) { forcedExtension = null; }
  53079. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53080. };
  53081. // Methods
  53082. CubeTexture.prototype.delayLoad = function () {
  53083. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53084. return;
  53085. }
  53086. var scene = this.getScene();
  53087. if (!scene) {
  53088. return;
  53089. }
  53090. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53091. this._texture = this._getFromCache(this.url, this._noMipmap);
  53092. if (!this._texture) {
  53093. if (this._prefiltered) {
  53094. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53095. }
  53096. else {
  53097. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53098. }
  53099. }
  53100. };
  53101. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53102. return this._textureMatrix;
  53103. };
  53104. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53105. this._textureMatrix = value;
  53106. };
  53107. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53108. var texture = BABYLON.SerializationHelper.Parse(function () {
  53109. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53110. }, parsedTexture, scene);
  53111. // Animations
  53112. if (parsedTexture.animations) {
  53113. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53114. var parsedAnimation = parsedTexture.animations[animationIndex];
  53115. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53116. }
  53117. }
  53118. return texture;
  53119. };
  53120. CubeTexture.prototype.clone = function () {
  53121. var _this = this;
  53122. return BABYLON.SerializationHelper.Clone(function () {
  53123. var scene = _this.getScene();
  53124. if (!scene) {
  53125. return _this;
  53126. }
  53127. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53128. }, this);
  53129. };
  53130. return CubeTexture;
  53131. }(BABYLON.BaseTexture));
  53132. BABYLON.CubeTexture = CubeTexture;
  53133. })(BABYLON || (BABYLON = {}));
  53134. //# sourceMappingURL=babylon.cubeTexture.js.map
  53135. var BABYLON;
  53136. (function (BABYLON) {
  53137. var RenderTargetTexture = /** @class */ (function (_super) {
  53138. __extends(RenderTargetTexture, _super);
  53139. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53140. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53141. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53142. if (isCube === void 0) { isCube = false; }
  53143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53144. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53145. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53146. if (isMulti === void 0) { isMulti = false; }
  53147. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53148. _this.isCube = isCube;
  53149. /**
  53150. * Use this list to define the list of mesh you want to render.
  53151. */
  53152. _this.renderList = new Array();
  53153. _this.renderParticles = true;
  53154. _this.renderSprites = false;
  53155. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53156. _this.ignoreCameraViewport = false;
  53157. // Events
  53158. /**
  53159. * An event triggered when the texture is unbind.
  53160. * @type {BABYLON.Observable}
  53161. */
  53162. _this.onBeforeBindObservable = new BABYLON.Observable();
  53163. /**
  53164. * An event triggered when the texture is unbind.
  53165. * @type {BABYLON.Observable}
  53166. */
  53167. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53168. /**
  53169. * An event triggered before rendering the texture
  53170. * @type {BABYLON.Observable}
  53171. */
  53172. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53173. /**
  53174. * An event triggered after rendering the texture
  53175. * @type {BABYLON.Observable}
  53176. */
  53177. _this.onAfterRenderObservable = new BABYLON.Observable();
  53178. /**
  53179. * An event triggered after the texture clear
  53180. * @type {BABYLON.Observable}
  53181. */
  53182. _this.onClearObservable = new BABYLON.Observable();
  53183. _this._currentRefreshId = -1;
  53184. _this._refreshRate = 1;
  53185. _this._samples = 1;
  53186. scene = _this.getScene();
  53187. if (!scene) {
  53188. return _this;
  53189. }
  53190. _this._engine = scene.getEngine();
  53191. _this.name = name;
  53192. _this.isRenderTarget = true;
  53193. _this._initialSizeParameter = size;
  53194. _this._processSizeParameter(size);
  53195. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53196. });
  53197. _this._generateMipMaps = generateMipMaps ? true : false;
  53198. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53199. // Rendering groups
  53200. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53201. if (isMulti) {
  53202. return _this;
  53203. }
  53204. _this._renderTargetOptions = {
  53205. generateMipMaps: generateMipMaps,
  53206. type: type,
  53207. samplingMode: samplingMode,
  53208. generateDepthBuffer: generateDepthBuffer,
  53209. generateStencilBuffer: generateStencilBuffer
  53210. };
  53211. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53212. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53213. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53214. }
  53215. if (isCube) {
  53216. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53217. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53218. _this._textureMatrix = BABYLON.Matrix.Identity();
  53219. }
  53220. else {
  53221. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53222. }
  53223. return _this;
  53224. }
  53225. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53226. get: function () {
  53227. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53228. },
  53229. enumerable: true,
  53230. configurable: true
  53231. });
  53232. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  53233. get: function () {
  53234. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  53235. },
  53236. enumerable: true,
  53237. configurable: true
  53238. });
  53239. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  53240. get: function () {
  53241. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  53242. },
  53243. enumerable: true,
  53244. configurable: true
  53245. });
  53246. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  53247. set: function (callback) {
  53248. if (this._onAfterUnbindObserver) {
  53249. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  53250. }
  53251. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  53252. },
  53253. enumerable: true,
  53254. configurable: true
  53255. });
  53256. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  53257. set: function (callback) {
  53258. if (this._onBeforeRenderObserver) {
  53259. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53260. }
  53261. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53262. },
  53263. enumerable: true,
  53264. configurable: true
  53265. });
  53266. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  53267. set: function (callback) {
  53268. if (this._onAfterRenderObserver) {
  53269. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53270. }
  53271. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53272. },
  53273. enumerable: true,
  53274. configurable: true
  53275. });
  53276. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  53277. set: function (callback) {
  53278. if (this._onClearObserver) {
  53279. this.onClearObservable.remove(this._onClearObserver);
  53280. }
  53281. this._onClearObserver = this.onClearObservable.add(callback);
  53282. },
  53283. enumerable: true,
  53284. configurable: true
  53285. });
  53286. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  53287. get: function () {
  53288. return this._renderTargetOptions;
  53289. },
  53290. enumerable: true,
  53291. configurable: true
  53292. });
  53293. RenderTargetTexture.prototype._onRatioRescale = function () {
  53294. if (this._sizeRatio) {
  53295. this.resize(this._initialSizeParameter);
  53296. }
  53297. };
  53298. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  53299. if (size.ratio) {
  53300. this._sizeRatio = size.ratio;
  53301. this._size = {
  53302. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  53303. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  53304. };
  53305. }
  53306. else {
  53307. this._size = size;
  53308. }
  53309. };
  53310. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  53311. get: function () {
  53312. return this._samples;
  53313. },
  53314. set: function (value) {
  53315. if (this._samples === value) {
  53316. return;
  53317. }
  53318. var scene = this.getScene();
  53319. if (!scene) {
  53320. return;
  53321. }
  53322. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  53323. },
  53324. enumerable: true,
  53325. configurable: true
  53326. });
  53327. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  53328. this._currentRefreshId = -1;
  53329. };
  53330. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  53331. get: function () {
  53332. return this._refreshRate;
  53333. },
  53334. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53335. set: function (value) {
  53336. this._refreshRate = value;
  53337. this.resetRefreshCounter();
  53338. },
  53339. enumerable: true,
  53340. configurable: true
  53341. });
  53342. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  53343. if (!this._postProcessManager) {
  53344. var scene = this.getScene();
  53345. if (!scene) {
  53346. return;
  53347. }
  53348. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  53349. this._postProcesses = new Array();
  53350. }
  53351. this._postProcesses.push(postProcess);
  53352. this._postProcesses[0].autoClear = false;
  53353. };
  53354. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  53355. if (!this._postProcesses) {
  53356. return;
  53357. }
  53358. if (dispose) {
  53359. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  53360. var postProcess = _a[_i];
  53361. postProcess.dispose();
  53362. }
  53363. }
  53364. this._postProcesses = [];
  53365. };
  53366. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  53367. if (!this._postProcesses) {
  53368. return;
  53369. }
  53370. var index = this._postProcesses.indexOf(postProcess);
  53371. if (index === -1) {
  53372. return;
  53373. }
  53374. this._postProcesses.splice(index, 1);
  53375. if (this._postProcesses.length > 0) {
  53376. this._postProcesses[0].autoClear = false;
  53377. }
  53378. };
  53379. RenderTargetTexture.prototype._shouldRender = function () {
  53380. if (this._currentRefreshId === -1) {
  53381. this._currentRefreshId = 1;
  53382. return true;
  53383. }
  53384. if (this.refreshRate === this._currentRefreshId) {
  53385. this._currentRefreshId = 1;
  53386. return true;
  53387. }
  53388. this._currentRefreshId++;
  53389. return false;
  53390. };
  53391. RenderTargetTexture.prototype.getRenderSize = function () {
  53392. if (this._size.width) {
  53393. return this._size.width;
  53394. }
  53395. return this._size;
  53396. };
  53397. RenderTargetTexture.prototype.getRenderWidth = function () {
  53398. if (this._size.width) {
  53399. return this._size.width;
  53400. }
  53401. return this._size;
  53402. };
  53403. RenderTargetTexture.prototype.getRenderHeight = function () {
  53404. if (this._size.width) {
  53405. return this._size.height;
  53406. }
  53407. return this._size;
  53408. };
  53409. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  53410. get: function () {
  53411. return true;
  53412. },
  53413. enumerable: true,
  53414. configurable: true
  53415. });
  53416. RenderTargetTexture.prototype.scale = function (ratio) {
  53417. var newSize = this.getRenderSize() * ratio;
  53418. this.resize(newSize);
  53419. };
  53420. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  53421. if (this.isCube) {
  53422. return this._textureMatrix;
  53423. }
  53424. return _super.prototype.getReflectionTextureMatrix.call(this);
  53425. };
  53426. RenderTargetTexture.prototype.resize = function (size) {
  53427. this.releaseInternalTexture();
  53428. var scene = this.getScene();
  53429. if (!scene) {
  53430. return;
  53431. }
  53432. this._processSizeParameter(size);
  53433. if (this.isCube) {
  53434. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  53435. }
  53436. else {
  53437. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  53438. }
  53439. };
  53440. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  53441. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  53442. if (dumpForDebug === void 0) { dumpForDebug = false; }
  53443. var scene = this.getScene();
  53444. if (!scene) {
  53445. return;
  53446. }
  53447. var engine = scene.getEngine();
  53448. if (this.useCameraPostProcesses !== undefined) {
  53449. useCameraPostProcess = this.useCameraPostProcesses;
  53450. }
  53451. if (this._waitingRenderList) {
  53452. this.renderList = [];
  53453. for (var index = 0; index < this._waitingRenderList.length; index++) {
  53454. var id = this._waitingRenderList[index];
  53455. var mesh_1 = scene.getMeshByID(id);
  53456. if (mesh_1) {
  53457. this.renderList.push(mesh_1);
  53458. }
  53459. }
  53460. delete this._waitingRenderList;
  53461. }
  53462. // Is predicate defined?
  53463. if (this.renderListPredicate) {
  53464. if (this.renderList) {
  53465. this.renderList.splice(0); // Clear previous renderList
  53466. }
  53467. else {
  53468. this.renderList = [];
  53469. }
  53470. var scene = this.getScene();
  53471. if (!scene) {
  53472. return;
  53473. }
  53474. var sceneMeshes = scene.meshes;
  53475. for (var index = 0; index < sceneMeshes.length; index++) {
  53476. var mesh = sceneMeshes[index];
  53477. if (this.renderListPredicate(mesh)) {
  53478. this.renderList.push(mesh);
  53479. }
  53480. }
  53481. }
  53482. this.onBeforeBindObservable.notifyObservers(this);
  53483. // Set custom projection.
  53484. // Needs to be before binding to prevent changing the aspect ratio.
  53485. var camera;
  53486. if (this.activeCamera) {
  53487. camera = this.activeCamera;
  53488. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53489. if (this.activeCamera !== scene.activeCamera) {
  53490. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  53491. }
  53492. }
  53493. else {
  53494. camera = scene.activeCamera;
  53495. if (camera) {
  53496. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53497. }
  53498. }
  53499. // Prepare renderingManager
  53500. this._renderingManager.reset();
  53501. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  53502. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  53503. var sceneRenderId = scene.getRenderId();
  53504. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  53505. var mesh = currentRenderList[meshIndex];
  53506. if (mesh) {
  53507. if (!mesh.isReady()) {
  53508. // Reset _currentRefreshId
  53509. this.resetRefreshCounter();
  53510. continue;
  53511. }
  53512. mesh._preActivateForIntermediateRendering(sceneRenderId);
  53513. var isMasked = void 0;
  53514. if (!this.renderList && camera) {
  53515. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  53516. }
  53517. else {
  53518. isMasked = false;
  53519. }
  53520. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  53521. mesh._activate(sceneRenderId);
  53522. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  53523. var subMesh = mesh.subMeshes[subIndex];
  53524. scene._activeIndices.addCount(subMesh.indexCount, false);
  53525. this._renderingManager.dispatch(subMesh, mesh);
  53526. }
  53527. }
  53528. }
  53529. }
  53530. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  53531. var particleSystem = scene.particleSystems[particleIndex];
  53532. var emitter = particleSystem.emitter;
  53533. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  53534. continue;
  53535. }
  53536. if (currentRenderList.indexOf(emitter) >= 0) {
  53537. this._renderingManager.dispatchParticles(particleSystem);
  53538. }
  53539. }
  53540. if (this.isCube) {
  53541. for (var face = 0; face < 6; face++) {
  53542. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53543. scene.incrementRenderId();
  53544. scene.resetCachedMaterial();
  53545. }
  53546. }
  53547. else {
  53548. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53549. }
  53550. this.onAfterUnbindObservable.notifyObservers(this);
  53551. if (scene.activeCamera) {
  53552. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  53553. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  53554. }
  53555. engine.setViewport(scene.activeCamera.viewport);
  53556. }
  53557. scene.resetCachedMaterial();
  53558. };
  53559. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  53560. var minimum = 128;
  53561. var x = renderDimension * scale;
  53562. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  53563. // Ensure we don't exceed the render dimension (while staying POT)
  53564. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  53565. };
  53566. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  53567. var _this = this;
  53568. if (!this._texture) {
  53569. return;
  53570. }
  53571. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  53572. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  53573. });
  53574. };
  53575. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  53576. var scene = this.getScene();
  53577. if (!scene) {
  53578. return;
  53579. }
  53580. var engine = scene.getEngine();
  53581. if (!this._texture) {
  53582. return;
  53583. }
  53584. // Bind
  53585. if (this._postProcessManager) {
  53586. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  53587. }
  53588. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  53589. if (this._texture) {
  53590. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  53591. }
  53592. }
  53593. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  53594. // Clear
  53595. if (this.onClearObservable.hasObservers()) {
  53596. this.onClearObservable.notifyObservers(engine);
  53597. }
  53598. else {
  53599. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  53600. }
  53601. if (!this._doNotChangeAspectRatio) {
  53602. scene.updateTransformMatrix(true);
  53603. }
  53604. // Render
  53605. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  53606. if (this._postProcessManager) {
  53607. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  53608. }
  53609. else if (useCameraPostProcess) {
  53610. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  53611. }
  53612. if (!this._doNotChangeAspectRatio) {
  53613. scene.updateTransformMatrix(true);
  53614. }
  53615. // Dump ?
  53616. if (dumpForDebug) {
  53617. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  53618. }
  53619. // Unbind
  53620. if (!this.isCube || faceIndex === 5) {
  53621. if (this.isCube) {
  53622. if (faceIndex === 5) {
  53623. engine.generateMipMapsForCubemap(this._texture);
  53624. }
  53625. }
  53626. this.unbindFrameBuffer(engine, faceIndex);
  53627. }
  53628. else {
  53629. this.onAfterRenderObservable.notifyObservers(faceIndex);
  53630. }
  53631. };
  53632. /**
  53633. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  53634. * This allowed control for front to back rendering or reversly depending of the special needs.
  53635. *
  53636. * @param renderingGroupId The rendering group id corresponding to its index
  53637. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  53638. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  53639. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  53640. */
  53641. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  53642. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  53643. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  53644. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  53645. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  53646. };
  53647. /**
  53648. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  53649. *
  53650. * @param renderingGroupId The rendering group id corresponding to its index
  53651. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  53652. */
  53653. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  53654. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  53655. };
  53656. RenderTargetTexture.prototype.clone = function () {
  53657. var textureSize = this.getSize();
  53658. 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);
  53659. // Base texture
  53660. newTexture.hasAlpha = this.hasAlpha;
  53661. newTexture.level = this.level;
  53662. // RenderTarget Texture
  53663. newTexture.coordinatesMode = this.coordinatesMode;
  53664. if (this.renderList) {
  53665. newTexture.renderList = this.renderList.slice(0);
  53666. }
  53667. return newTexture;
  53668. };
  53669. RenderTargetTexture.prototype.serialize = function () {
  53670. if (!this.name) {
  53671. return null;
  53672. }
  53673. var serializationObject = _super.prototype.serialize.call(this);
  53674. serializationObject.renderTargetSize = this.getRenderSize();
  53675. serializationObject.renderList = [];
  53676. if (this.renderList) {
  53677. for (var index = 0; index < this.renderList.length; index++) {
  53678. serializationObject.renderList.push(this.renderList[index].id);
  53679. }
  53680. }
  53681. return serializationObject;
  53682. };
  53683. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  53684. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  53685. var objBuffer = this.getInternalTexture();
  53686. var scene = this.getScene();
  53687. if (objBuffer && scene) {
  53688. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  53689. }
  53690. };
  53691. RenderTargetTexture.prototype.dispose = function () {
  53692. if (this._postProcessManager) {
  53693. this._postProcessManager.dispose();
  53694. this._postProcessManager = null;
  53695. }
  53696. this.clearPostProcesses(true);
  53697. if (this._resizeObserver) {
  53698. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  53699. this._resizeObserver = null;
  53700. }
  53701. this.renderList = null;
  53702. // Remove from custom render targets
  53703. var scene = this.getScene();
  53704. if (!scene) {
  53705. return;
  53706. }
  53707. var index = scene.customRenderTargets.indexOf(this);
  53708. if (index >= 0) {
  53709. scene.customRenderTargets.splice(index, 1);
  53710. }
  53711. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  53712. var camera = _a[_i];
  53713. index = camera.customRenderTargets.indexOf(this);
  53714. if (index >= 0) {
  53715. camera.customRenderTargets.splice(index, 1);
  53716. }
  53717. }
  53718. _super.prototype.dispose.call(this);
  53719. };
  53720. RenderTargetTexture.prototype._rebuild = function () {
  53721. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  53722. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  53723. }
  53724. if (this._postProcessManager) {
  53725. this._postProcessManager._rebuild();
  53726. }
  53727. };
  53728. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  53729. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  53730. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  53731. return RenderTargetTexture;
  53732. }(BABYLON.Texture));
  53733. BABYLON.RenderTargetTexture = RenderTargetTexture;
  53734. })(BABYLON || (BABYLON = {}));
  53735. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  53736. var BABYLON;
  53737. (function (BABYLON) {
  53738. ;
  53739. var MultiRenderTarget = /** @class */ (function (_super) {
  53740. __extends(MultiRenderTarget, _super);
  53741. function MultiRenderTarget(name, size, count, scene, options) {
  53742. var _this = this;
  53743. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  53744. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  53745. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  53746. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  53747. _this._engine = scene.getEngine();
  53748. if (!_this.isSupported) {
  53749. _this.dispose();
  53750. return;
  53751. }
  53752. var types = [];
  53753. var samplingModes = [];
  53754. for (var i = 0; i < count; i++) {
  53755. if (options && options.types && options.types[i] !== undefined) {
  53756. types.push(options.types[i]);
  53757. }
  53758. else {
  53759. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53760. }
  53761. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  53762. samplingModes.push(options.samplingModes[i]);
  53763. }
  53764. else {
  53765. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53766. }
  53767. }
  53768. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  53769. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  53770. _this._size = size;
  53771. _this._multiRenderTargetOptions = {
  53772. samplingModes: samplingModes,
  53773. generateMipMaps: generateMipMaps,
  53774. generateDepthBuffer: generateDepthBuffer,
  53775. generateStencilBuffer: generateStencilBuffer,
  53776. generateDepthTexture: generateDepthTexture,
  53777. types: types,
  53778. textureCount: count
  53779. };
  53780. _this._createInternalTextures();
  53781. _this._createTextures();
  53782. return _this;
  53783. }
  53784. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  53785. get: function () {
  53786. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  53787. },
  53788. enumerable: true,
  53789. configurable: true
  53790. });
  53791. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  53792. get: function () {
  53793. return this._textures;
  53794. },
  53795. enumerable: true,
  53796. configurable: true
  53797. });
  53798. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  53799. get: function () {
  53800. return this._textures[this._textures.length - 1];
  53801. },
  53802. enumerable: true,
  53803. configurable: true
  53804. });
  53805. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  53806. set: function (wrap) {
  53807. if (this._textures) {
  53808. for (var i = 0; i < this._textures.length; i++) {
  53809. this._textures[i].wrapU = wrap;
  53810. }
  53811. }
  53812. },
  53813. enumerable: true,
  53814. configurable: true
  53815. });
  53816. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  53817. set: function (wrap) {
  53818. if (this._textures) {
  53819. for (var i = 0; i < this._textures.length; i++) {
  53820. this._textures[i].wrapV = wrap;
  53821. }
  53822. }
  53823. },
  53824. enumerable: true,
  53825. configurable: true
  53826. });
  53827. MultiRenderTarget.prototype._rebuild = function () {
  53828. this.releaseInternalTextures();
  53829. this._createInternalTextures();
  53830. for (var i = 0; i < this._internalTextures.length; i++) {
  53831. var texture = this._textures[i];
  53832. texture._texture = this._internalTextures[i];
  53833. }
  53834. // Keeps references to frame buffer and stencil/depth buffer
  53835. this._texture = this._internalTextures[0];
  53836. };
  53837. MultiRenderTarget.prototype._createInternalTextures = function () {
  53838. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  53839. };
  53840. MultiRenderTarget.prototype._createTextures = function () {
  53841. this._textures = [];
  53842. for (var i = 0; i < this._internalTextures.length; i++) {
  53843. var texture = new BABYLON.Texture(null, this.getScene());
  53844. texture._texture = this._internalTextures[i];
  53845. this._textures.push(texture);
  53846. }
  53847. // Keeps references to frame buffer and stencil/depth buffer
  53848. this._texture = this._internalTextures[0];
  53849. };
  53850. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  53851. get: function () {
  53852. return this._samples;
  53853. },
  53854. set: function (value) {
  53855. if (this._samples === value) {
  53856. return;
  53857. }
  53858. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  53859. },
  53860. enumerable: true,
  53861. configurable: true
  53862. });
  53863. MultiRenderTarget.prototype.resize = function (size) {
  53864. this.releaseInternalTextures();
  53865. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  53866. this._createInternalTextures();
  53867. };
  53868. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  53869. var _this = this;
  53870. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  53871. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  53872. });
  53873. };
  53874. MultiRenderTarget.prototype.dispose = function () {
  53875. this.releaseInternalTextures();
  53876. _super.prototype.dispose.call(this);
  53877. };
  53878. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  53879. if (!this._internalTextures) {
  53880. return;
  53881. }
  53882. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  53883. if (this._internalTextures[i] !== undefined) {
  53884. this._internalTextures[i].dispose();
  53885. this._internalTextures.splice(i, 1);
  53886. }
  53887. }
  53888. };
  53889. return MultiRenderTarget;
  53890. }(BABYLON.RenderTargetTexture));
  53891. BABYLON.MultiRenderTarget = MultiRenderTarget;
  53892. })(BABYLON || (BABYLON = {}));
  53893. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  53894. var BABYLON;
  53895. (function (BABYLON) {
  53896. var MirrorTexture = /** @class */ (function (_super) {
  53897. __extends(MirrorTexture, _super);
  53898. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  53899. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53901. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53902. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  53903. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  53904. _this._transformMatrix = BABYLON.Matrix.Zero();
  53905. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  53906. _this._adaptiveBlurKernel = 0;
  53907. _this._blurKernelX = 0;
  53908. _this._blurKernelY = 0;
  53909. _this._blurRatio = 1.0;
  53910. _this.ignoreCameraViewport = true;
  53911. _this.onBeforeRenderObservable.add(function () {
  53912. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  53913. _this._savedViewMatrix = scene.getViewMatrix();
  53914. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  53915. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  53916. scene.clipPlane = _this.mirrorPlane;
  53917. scene.getEngine().cullBackFaces = false;
  53918. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  53919. });
  53920. _this.onAfterRenderObservable.add(function () {
  53921. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  53922. scene.getEngine().cullBackFaces = true;
  53923. scene._mirroredCameraPosition = null;
  53924. delete scene.clipPlane;
  53925. });
  53926. return _this;
  53927. }
  53928. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  53929. get: function () {
  53930. return this._blurRatio;
  53931. },
  53932. set: function (value) {
  53933. if (this._blurRatio === value) {
  53934. return;
  53935. }
  53936. this._blurRatio = value;
  53937. this._preparePostProcesses();
  53938. },
  53939. enumerable: true,
  53940. configurable: true
  53941. });
  53942. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  53943. set: function (value) {
  53944. this._adaptiveBlurKernel = value;
  53945. this._autoComputeBlurKernel();
  53946. },
  53947. enumerable: true,
  53948. configurable: true
  53949. });
  53950. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  53951. set: function (value) {
  53952. this.blurKernelX = value;
  53953. this.blurKernelY = value;
  53954. },
  53955. enumerable: true,
  53956. configurable: true
  53957. });
  53958. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  53959. get: function () {
  53960. return this._blurKernelX;
  53961. },
  53962. set: function (value) {
  53963. if (this._blurKernelX === value) {
  53964. return;
  53965. }
  53966. this._blurKernelX = value;
  53967. this._preparePostProcesses();
  53968. },
  53969. enumerable: true,
  53970. configurable: true
  53971. });
  53972. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  53973. get: function () {
  53974. return this._blurKernelY;
  53975. },
  53976. set: function (value) {
  53977. if (this._blurKernelY === value) {
  53978. return;
  53979. }
  53980. this._blurKernelY = value;
  53981. this._preparePostProcesses();
  53982. },
  53983. enumerable: true,
  53984. configurable: true
  53985. });
  53986. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  53987. var engine = this.getScene().getEngine();
  53988. var dw = this.getRenderWidth() / engine.getRenderWidth();
  53989. var dh = this.getRenderHeight() / engine.getRenderHeight();
  53990. this.blurKernelX = this._adaptiveBlurKernel * dw;
  53991. this.blurKernelY = this._adaptiveBlurKernel * dh;
  53992. };
  53993. MirrorTexture.prototype._onRatioRescale = function () {
  53994. if (this._sizeRatio) {
  53995. this.resize(this._initialSizeParameter);
  53996. if (!this._adaptiveBlurKernel) {
  53997. this._preparePostProcesses();
  53998. }
  53999. }
  54000. if (this._adaptiveBlurKernel) {
  54001. this._autoComputeBlurKernel();
  54002. }
  54003. };
  54004. MirrorTexture.prototype._preparePostProcesses = function () {
  54005. this.clearPostProcesses(true);
  54006. if (this._blurKernelX && this._blurKernelY) {
  54007. var engine = this.getScene().getEngine();
  54008. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54009. 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);
  54010. this._blurX.autoClear = false;
  54011. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54012. this._blurX.outputTexture = this._texture;
  54013. }
  54014. else {
  54015. this._blurX.alwaysForcePOT = true;
  54016. }
  54017. 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);
  54018. this._blurY.autoClear = false;
  54019. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54020. this.addPostProcess(this._blurX);
  54021. this.addPostProcess(this._blurY);
  54022. }
  54023. else {
  54024. if (this._blurY) {
  54025. this.removePostProcess(this._blurY);
  54026. this._blurY.dispose();
  54027. this._blurY = null;
  54028. }
  54029. if (this._blurX) {
  54030. this.removePostProcess(this._blurX);
  54031. this._blurX.dispose();
  54032. this._blurX = null;
  54033. }
  54034. }
  54035. };
  54036. MirrorTexture.prototype.clone = function () {
  54037. var scene = this.getScene();
  54038. if (!scene) {
  54039. return this;
  54040. }
  54041. var textureSize = this.getSize();
  54042. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54043. // Base texture
  54044. newTexture.hasAlpha = this.hasAlpha;
  54045. newTexture.level = this.level;
  54046. // Mirror Texture
  54047. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54048. if (this.renderList) {
  54049. newTexture.renderList = this.renderList.slice(0);
  54050. }
  54051. return newTexture;
  54052. };
  54053. MirrorTexture.prototype.serialize = function () {
  54054. if (!this.name) {
  54055. return null;
  54056. }
  54057. var serializationObject = _super.prototype.serialize.call(this);
  54058. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54059. return serializationObject;
  54060. };
  54061. return MirrorTexture;
  54062. }(BABYLON.RenderTargetTexture));
  54063. BABYLON.MirrorTexture = MirrorTexture;
  54064. })(BABYLON || (BABYLON = {}));
  54065. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54066. var BABYLON;
  54067. (function (BABYLON) {
  54068. /**
  54069. * Creates a refraction texture used by refraction channel of the standard material.
  54070. * @param name the texture name
  54071. * @param size size of the underlying texture
  54072. * @param scene root scene
  54073. */
  54074. var RefractionTexture = /** @class */ (function (_super) {
  54075. __extends(RefractionTexture, _super);
  54076. function RefractionTexture(name, size, scene, generateMipMaps) {
  54077. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54078. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54079. _this.depth = 2.0;
  54080. _this.onBeforeRenderObservable.add(function () {
  54081. scene.clipPlane = _this.refractionPlane;
  54082. });
  54083. _this.onAfterRenderObservable.add(function () {
  54084. delete scene.clipPlane;
  54085. });
  54086. return _this;
  54087. }
  54088. RefractionTexture.prototype.clone = function () {
  54089. var scene = this.getScene();
  54090. if (!scene) {
  54091. return this;
  54092. }
  54093. var textureSize = this.getSize();
  54094. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54095. // Base texture
  54096. newTexture.hasAlpha = this.hasAlpha;
  54097. newTexture.level = this.level;
  54098. // Refraction Texture
  54099. newTexture.refractionPlane = this.refractionPlane.clone();
  54100. if (this.renderList) {
  54101. newTexture.renderList = this.renderList.slice(0);
  54102. }
  54103. newTexture.depth = this.depth;
  54104. return newTexture;
  54105. };
  54106. RefractionTexture.prototype.serialize = function () {
  54107. if (!this.name) {
  54108. return null;
  54109. }
  54110. var serializationObject = _super.prototype.serialize.call(this);
  54111. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54112. serializationObject.depth = this.depth;
  54113. return serializationObject;
  54114. };
  54115. return RefractionTexture;
  54116. }(BABYLON.RenderTargetTexture));
  54117. BABYLON.RefractionTexture = RefractionTexture;
  54118. })(BABYLON || (BABYLON = {}));
  54119. //# sourceMappingURL=babylon.refractionTexture.js.map
  54120. var BABYLON;
  54121. (function (BABYLON) {
  54122. var DynamicTexture = /** @class */ (function (_super) {
  54123. __extends(DynamicTexture, _super);
  54124. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54125. if (scene === void 0) { scene = null; }
  54126. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54127. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54128. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54129. _this.name = name;
  54130. _this._engine = _this.getScene().getEngine();
  54131. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54132. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54133. _this._generateMipMaps = generateMipMaps;
  54134. if (options.getContext) {
  54135. _this._canvas = options;
  54136. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54137. }
  54138. else {
  54139. _this._canvas = document.createElement("canvas");
  54140. if (options.width) {
  54141. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54142. }
  54143. else {
  54144. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54145. }
  54146. }
  54147. var textureSize = _this.getSize();
  54148. _this._canvas.width = textureSize.width;
  54149. _this._canvas.height = textureSize.height;
  54150. _this._context = _this._canvas.getContext("2d");
  54151. return _this;
  54152. }
  54153. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54154. get: function () {
  54155. return true;
  54156. },
  54157. enumerable: true,
  54158. configurable: true
  54159. });
  54160. DynamicTexture.prototype._recreate = function (textureSize) {
  54161. this._canvas.width = textureSize.width;
  54162. this._canvas.height = textureSize.height;
  54163. this.releaseInternalTexture();
  54164. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54165. };
  54166. DynamicTexture.prototype.scale = function (ratio) {
  54167. var textureSize = this.getSize();
  54168. textureSize.width *= ratio;
  54169. textureSize.height *= ratio;
  54170. this._recreate(textureSize);
  54171. };
  54172. DynamicTexture.prototype.scaleTo = function (width, height) {
  54173. var textureSize = this.getSize();
  54174. textureSize.width = width;
  54175. textureSize.height = height;
  54176. this._recreate(textureSize);
  54177. };
  54178. DynamicTexture.prototype.getContext = function () {
  54179. return this._context;
  54180. };
  54181. DynamicTexture.prototype.clear = function () {
  54182. var size = this.getSize();
  54183. this._context.fillRect(0, 0, size.width, size.height);
  54184. };
  54185. DynamicTexture.prototype.update = function (invertY) {
  54186. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54187. };
  54188. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54189. if (update === void 0) { update = true; }
  54190. var size = this.getSize();
  54191. if (clearColor) {
  54192. this._context.fillStyle = clearColor;
  54193. this._context.fillRect(0, 0, size.width, size.height);
  54194. }
  54195. this._context.font = font;
  54196. if (x === null || x === undefined) {
  54197. var textSize = this._context.measureText(text);
  54198. x = (size.width - textSize.width) / 2;
  54199. }
  54200. if (y === null || y === undefined) {
  54201. var fontSize = parseInt((font.replace(/\D/g, '')));
  54202. ;
  54203. y = (size.height / 2) + (fontSize / 3.65);
  54204. }
  54205. this._context.fillStyle = color;
  54206. this._context.fillText(text, x, y);
  54207. if (update) {
  54208. this.update(invertY);
  54209. }
  54210. };
  54211. DynamicTexture.prototype.clone = function () {
  54212. var scene = this.getScene();
  54213. if (!scene) {
  54214. return this;
  54215. }
  54216. var textureSize = this.getSize();
  54217. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54218. // Base texture
  54219. newTexture.hasAlpha = this.hasAlpha;
  54220. newTexture.level = this.level;
  54221. // Dynamic Texture
  54222. newTexture.wrapU = this.wrapU;
  54223. newTexture.wrapV = this.wrapV;
  54224. return newTexture;
  54225. };
  54226. DynamicTexture.prototype._rebuild = function () {
  54227. this.update();
  54228. };
  54229. return DynamicTexture;
  54230. }(BABYLON.Texture));
  54231. BABYLON.DynamicTexture = DynamicTexture;
  54232. })(BABYLON || (BABYLON = {}));
  54233. //# sourceMappingURL=babylon.dynamicTexture.js.map
  54234. var BABYLON;
  54235. (function (BABYLON) {
  54236. var VideoTexture = /** @class */ (function (_super) {
  54237. __extends(VideoTexture, _super);
  54238. /**
  54239. * Creates a video texture.
  54240. * Sample : https://doc.babylonjs.com/how_to/video_texture
  54241. * @param {string | null} name optional name, will detect from video source, if not defined
  54242. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  54243. * @param {BABYLON.Scene} scene is obviously the current scene.
  54244. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  54245. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  54246. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  54247. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  54248. */
  54249. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  54250. if (generateMipMaps === void 0) { generateMipMaps = false; }
  54251. if (invertY === void 0) { invertY = false; }
  54252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54253. if (settings === void 0) { settings = {
  54254. autoPlay: true,
  54255. loop: true,
  54256. autoUpdateTexture: true,
  54257. }; }
  54258. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54259. _this._createInternalTexture = function () {
  54260. if (_this._texture != null) {
  54261. return;
  54262. }
  54263. if (!_this._engine.needPOTTextures ||
  54264. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  54265. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54266. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54267. }
  54268. else {
  54269. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54270. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54271. _this._generateMipMaps = false;
  54272. }
  54273. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  54274. _this._texture.width;
  54275. _this._updateInternalTexture();
  54276. _this._texture.isReady = true;
  54277. };
  54278. _this.reset = function () {
  54279. if (_this._texture == null) {
  54280. return;
  54281. }
  54282. _this._texture.dispose();
  54283. _this._texture = null;
  54284. };
  54285. _this._updateInternalTexture = function (e) {
  54286. if (_this._texture == null || !_this._texture.isReady) {
  54287. return;
  54288. }
  54289. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  54290. return;
  54291. }
  54292. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  54293. };
  54294. _this._engine = _this.getScene().getEngine();
  54295. _this._generateMipMaps = generateMipMaps;
  54296. _this._samplingMode = samplingMode;
  54297. _this.autoUpdateTexture = settings.autoUpdateTexture;
  54298. _this.name = name || _this._getName(src);
  54299. _this.video = _this._getVideo(src);
  54300. if (settings.autoPlay !== undefined) {
  54301. _this.video.autoplay = settings.autoPlay;
  54302. }
  54303. if (settings.loop !== undefined) {
  54304. _this.video.loop = settings.loop;
  54305. }
  54306. _this.video.addEventListener("canplay", _this._createInternalTexture);
  54307. _this.video.addEventListener("paused", _this._updateInternalTexture);
  54308. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  54309. _this.video.addEventListener("emptied", _this.reset);
  54310. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  54311. _this._createInternalTexture();
  54312. }
  54313. return _this;
  54314. }
  54315. VideoTexture.prototype._getName = function (src) {
  54316. if (src instanceof HTMLVideoElement) {
  54317. return src.currentSrc;
  54318. }
  54319. if (typeof src === "object") {
  54320. return src.toString();
  54321. }
  54322. return src;
  54323. };
  54324. ;
  54325. VideoTexture.prototype._getVideo = function (src) {
  54326. if (src instanceof HTMLVideoElement) {
  54327. return src;
  54328. }
  54329. var video = document.createElement("video");
  54330. if (typeof src === "string") {
  54331. video.src = src;
  54332. }
  54333. else {
  54334. src.forEach(function (url) {
  54335. var source = document.createElement("source");
  54336. source.src = url;
  54337. video.appendChild(source);
  54338. });
  54339. }
  54340. return video;
  54341. };
  54342. ;
  54343. /**
  54344. * Internal method to initiate `update`.
  54345. */
  54346. VideoTexture.prototype._rebuild = function () {
  54347. this.update();
  54348. };
  54349. /**
  54350. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  54351. */
  54352. VideoTexture.prototype.update = function () {
  54353. if (!this.autoUpdateTexture) {
  54354. // Expecting user to call `updateTexture` manually
  54355. return;
  54356. }
  54357. this.updateTexture(true);
  54358. };
  54359. /**
  54360. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  54361. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  54362. */
  54363. VideoTexture.prototype.updateTexture = function (isVisible) {
  54364. if (!isVisible) {
  54365. return;
  54366. }
  54367. if (this.video.paused) {
  54368. return;
  54369. }
  54370. this._updateInternalTexture();
  54371. };
  54372. /**
  54373. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  54374. * @param url New url.
  54375. */
  54376. VideoTexture.prototype.updateURL = function (url) {
  54377. this.video.src = url;
  54378. };
  54379. VideoTexture.prototype.dispose = function () {
  54380. _super.prototype.dispose.call(this);
  54381. this.video.removeEventListener("canplay", this._createInternalTexture);
  54382. this.video.removeEventListener("paused", this._updateInternalTexture);
  54383. this.video.removeEventListener("seeked", this._updateInternalTexture);
  54384. this.video.removeEventListener("emptied", this.reset);
  54385. };
  54386. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  54387. var video = document.createElement("video");
  54388. var constraintsDeviceId;
  54389. if (constraints && constraints.deviceId) {
  54390. constraintsDeviceId = {
  54391. exact: constraints.deviceId,
  54392. };
  54393. }
  54394. navigator.getUserMedia =
  54395. navigator.getUserMedia ||
  54396. navigator.webkitGetUserMedia ||
  54397. navigator.mozGetUserMedia ||
  54398. navigator.msGetUserMedia;
  54399. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  54400. if (navigator.getUserMedia) {
  54401. navigator.getUserMedia({
  54402. video: {
  54403. deviceId: constraintsDeviceId,
  54404. width: {
  54405. min: (constraints && constraints.minWidth) || 256,
  54406. max: (constraints && constraints.maxWidth) || 640,
  54407. },
  54408. height: {
  54409. min: (constraints && constraints.minHeight) || 256,
  54410. max: (constraints && constraints.maxHeight) || 480,
  54411. },
  54412. },
  54413. }, function (stream) {
  54414. if (video.mozSrcObject !== undefined) {
  54415. // hack for Firefox < 19
  54416. video.mozSrcObject = stream;
  54417. }
  54418. else {
  54419. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  54420. }
  54421. video.play();
  54422. if (onReady) {
  54423. onReady(new VideoTexture("video", video, scene, true, true));
  54424. }
  54425. }, function (e) {
  54426. BABYLON.Tools.Error(e.name);
  54427. });
  54428. }
  54429. };
  54430. return VideoTexture;
  54431. }(BABYLON.Texture));
  54432. BABYLON.VideoTexture = VideoTexture;
  54433. })(BABYLON || (BABYLON = {}));
  54434. //# sourceMappingURL=babylon.videoTexture.js.map
  54435. var BABYLON;
  54436. (function (BABYLON) {
  54437. var RawTexture = /** @class */ (function (_super) {
  54438. __extends(RawTexture, _super);
  54439. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  54440. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54441. if (invertY === void 0) { invertY = false; }
  54442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54443. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54444. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54445. _this.format = format;
  54446. _this._engine = scene.getEngine();
  54447. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  54448. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54449. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54450. return _this;
  54451. }
  54452. RawTexture.prototype.update = function (data) {
  54453. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  54454. };
  54455. // Statics
  54456. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54457. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54458. if (invertY === void 0) { invertY = false; }
  54459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54460. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54461. };
  54462. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54463. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54464. if (invertY === void 0) { invertY = false; }
  54465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54466. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54467. };
  54468. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54469. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54470. if (invertY === void 0) { invertY = false; }
  54471. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54472. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54473. };
  54474. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54475. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54476. if (invertY === void 0) { invertY = false; }
  54477. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54478. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54479. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  54480. };
  54481. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54482. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54483. if (invertY === void 0) { invertY = false; }
  54484. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54485. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54486. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  54487. };
  54488. return RawTexture;
  54489. }(BABYLON.Texture));
  54490. BABYLON.RawTexture = RawTexture;
  54491. })(BABYLON || (BABYLON = {}));
  54492. //# sourceMappingURL=babylon.rawTexture.js.map
  54493. var BABYLON;
  54494. (function (BABYLON) {
  54495. var PostProcess = /** @class */ (function () {
  54496. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  54497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  54498. if (defines === void 0) { defines = null; }
  54499. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54500. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  54501. if (blockCompilation === void 0) { blockCompilation = false; }
  54502. this.name = name;
  54503. this.width = -1;
  54504. this.height = -1;
  54505. this.autoClear = true;
  54506. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  54507. this.animations = new Array();
  54508. /*
  54509. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  54510. Can only be used on a single postprocess or on the last one of a chain.
  54511. */
  54512. this.enablePixelPerfectMode = false;
  54513. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  54514. this.alwaysForcePOT = false;
  54515. this.samples = 1;
  54516. this.adaptScaleToCurrentViewport = false;
  54517. this._reusable = false;
  54518. this._textures = new BABYLON.SmartArray(2);
  54519. this._currentRenderTextureInd = 0;
  54520. this._scaleRatio = new BABYLON.Vector2(1, 1);
  54521. this._texelSize = BABYLON.Vector2.Zero();
  54522. // Events
  54523. /**
  54524. * An event triggered when the postprocess is activated.
  54525. * @type {BABYLON.Observable}
  54526. */
  54527. this.onActivateObservable = new BABYLON.Observable();
  54528. /**
  54529. * An event triggered when the postprocess changes its size.
  54530. * @type {BABYLON.Observable}
  54531. */
  54532. this.onSizeChangedObservable = new BABYLON.Observable();
  54533. /**
  54534. * An event triggered when the postprocess applies its effect.
  54535. * @type {BABYLON.Observable}
  54536. */
  54537. this.onApplyObservable = new BABYLON.Observable();
  54538. /**
  54539. * An event triggered before rendering the postprocess
  54540. * @type {BABYLON.Observable}
  54541. */
  54542. this.onBeforeRenderObservable = new BABYLON.Observable();
  54543. /**
  54544. * An event triggered after rendering the postprocess
  54545. * @type {BABYLON.Observable}
  54546. */
  54547. this.onAfterRenderObservable = new BABYLON.Observable();
  54548. if (camera != null) {
  54549. this._camera = camera;
  54550. this._scene = camera.getScene();
  54551. camera.attachPostProcess(this);
  54552. this._engine = this._scene.getEngine();
  54553. this._scene.postProcesses.push(this);
  54554. }
  54555. else if (engine) {
  54556. this._engine = engine;
  54557. this._engine.postProcesses.push(this);
  54558. }
  54559. this._options = options;
  54560. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  54561. this._reusable = reusable || false;
  54562. this._textureType = textureType;
  54563. this._samplers = samplers || [];
  54564. this._samplers.push("textureSampler");
  54565. this._fragmentUrl = fragmentUrl;
  54566. this._vertexUrl = vertexUrl;
  54567. this._parameters = parameters || [];
  54568. this._parameters.push("scale");
  54569. this._indexParameters = indexParameters;
  54570. if (!blockCompilation) {
  54571. this.updateEffect(defines);
  54572. }
  54573. }
  54574. Object.defineProperty(PostProcess.prototype, "onActivate", {
  54575. set: function (callback) {
  54576. if (this._onActivateObserver) {
  54577. this.onActivateObservable.remove(this._onActivateObserver);
  54578. }
  54579. if (callback) {
  54580. this._onActivateObserver = this.onActivateObservable.add(callback);
  54581. }
  54582. },
  54583. enumerable: true,
  54584. configurable: true
  54585. });
  54586. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  54587. set: function (callback) {
  54588. if (this._onSizeChangedObserver) {
  54589. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  54590. }
  54591. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  54592. },
  54593. enumerable: true,
  54594. configurable: true
  54595. });
  54596. Object.defineProperty(PostProcess.prototype, "onApply", {
  54597. set: function (callback) {
  54598. if (this._onApplyObserver) {
  54599. this.onApplyObservable.remove(this._onApplyObserver);
  54600. }
  54601. this._onApplyObserver = this.onApplyObservable.add(callback);
  54602. },
  54603. enumerable: true,
  54604. configurable: true
  54605. });
  54606. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  54607. set: function (callback) {
  54608. if (this._onBeforeRenderObserver) {
  54609. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  54610. }
  54611. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  54612. },
  54613. enumerable: true,
  54614. configurable: true
  54615. });
  54616. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  54617. set: function (callback) {
  54618. if (this._onAfterRenderObserver) {
  54619. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  54620. }
  54621. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  54622. },
  54623. enumerable: true,
  54624. configurable: true
  54625. });
  54626. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  54627. get: function () {
  54628. return this._textures.data[this._currentRenderTextureInd];
  54629. },
  54630. set: function (value) {
  54631. this._forcedOutputTexture = value;
  54632. },
  54633. enumerable: true,
  54634. configurable: true
  54635. });
  54636. PostProcess.prototype.getCamera = function () {
  54637. return this._camera;
  54638. };
  54639. Object.defineProperty(PostProcess.prototype, "texelSize", {
  54640. get: function () {
  54641. if (this._shareOutputWithPostProcess) {
  54642. return this._shareOutputWithPostProcess.texelSize;
  54643. }
  54644. if (this._forcedOutputTexture) {
  54645. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  54646. }
  54647. return this._texelSize;
  54648. },
  54649. enumerable: true,
  54650. configurable: true
  54651. });
  54652. PostProcess.prototype.getEngine = function () {
  54653. return this._engine;
  54654. };
  54655. PostProcess.prototype.getEffect = function () {
  54656. return this._effect;
  54657. };
  54658. PostProcess.prototype.shareOutputWith = function (postProcess) {
  54659. this._disposeTextures();
  54660. this._shareOutputWithPostProcess = postProcess;
  54661. return this;
  54662. };
  54663. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  54664. if (defines === void 0) { defines = null; }
  54665. if (uniforms === void 0) { uniforms = null; }
  54666. if (samplers === void 0) { samplers = null; }
  54667. 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);
  54668. };
  54669. PostProcess.prototype.isReusable = function () {
  54670. return this._reusable;
  54671. };
  54672. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  54673. PostProcess.prototype.markTextureDirty = function () {
  54674. this.width = -1;
  54675. };
  54676. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  54677. var _this = this;
  54678. if (sourceTexture === void 0) { sourceTexture = null; }
  54679. camera = camera || this._camera;
  54680. var scene = camera.getScene();
  54681. var engine = scene.getEngine();
  54682. var maxSize = engine.getCaps().maxTextureSize;
  54683. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  54684. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  54685. var desiredWidth = (this._options.width || requiredWidth);
  54686. var desiredHeight = this._options.height || requiredHeight;
  54687. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  54688. if (this.adaptScaleToCurrentViewport) {
  54689. var currentViewport = engine.currentViewport;
  54690. if (currentViewport) {
  54691. desiredWidth *= currentViewport.width;
  54692. desiredHeight *= currentViewport.height;
  54693. }
  54694. }
  54695. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  54696. if (!this._options.width) {
  54697. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  54698. }
  54699. if (!this._options.height) {
  54700. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  54701. }
  54702. }
  54703. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  54704. if (this._textures.length > 0) {
  54705. for (var i = 0; i < this._textures.length; i++) {
  54706. this._engine._releaseTexture(this._textures.data[i]);
  54707. }
  54708. this._textures.reset();
  54709. }
  54710. this.width = desiredWidth;
  54711. this.height = desiredHeight;
  54712. var textureSize = { width: this.width, height: this.height };
  54713. var textureOptions = {
  54714. generateMipMaps: false,
  54715. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  54716. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  54717. samplingMode: this.renderTargetSamplingMode,
  54718. type: this._textureType
  54719. };
  54720. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54721. if (this._reusable) {
  54722. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  54723. }
  54724. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  54725. this.onSizeChangedObservable.notifyObservers(this);
  54726. }
  54727. this._textures.forEach(function (texture) {
  54728. if (texture.samples !== _this.samples) {
  54729. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  54730. }
  54731. });
  54732. }
  54733. var target;
  54734. if (this._shareOutputWithPostProcess) {
  54735. target = this._shareOutputWithPostProcess.outputTexture;
  54736. }
  54737. else if (this._forcedOutputTexture) {
  54738. target = this._forcedOutputTexture;
  54739. this.width = this._forcedOutputTexture.width;
  54740. this.height = this._forcedOutputTexture.height;
  54741. }
  54742. else {
  54743. target = this.outputTexture;
  54744. }
  54745. if (this.enablePixelPerfectMode) {
  54746. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  54747. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  54748. }
  54749. else {
  54750. this._scaleRatio.copyFromFloats(1, 1);
  54751. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  54752. }
  54753. this.onActivateObservable.notifyObservers(camera);
  54754. // Clear
  54755. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  54756. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  54757. }
  54758. if (this._reusable) {
  54759. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  54760. }
  54761. };
  54762. Object.defineProperty(PostProcess.prototype, "isSupported", {
  54763. get: function () {
  54764. return this._effect.isSupported;
  54765. },
  54766. enumerable: true,
  54767. configurable: true
  54768. });
  54769. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  54770. get: function () {
  54771. if (this._shareOutputWithPostProcess) {
  54772. return this._shareOutputWithPostProcess.aspectRatio;
  54773. }
  54774. if (this._forcedOutputTexture) {
  54775. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  54776. }
  54777. return this.width / this.height;
  54778. },
  54779. enumerable: true,
  54780. configurable: true
  54781. });
  54782. /**
  54783. * Get a value indicating if the post-process is ready to be used
  54784. * @returns true if the post-process is ready (shader is compiled)
  54785. */
  54786. PostProcess.prototype.isReady = function () {
  54787. return this._effect && this._effect.isReady();
  54788. };
  54789. PostProcess.prototype.apply = function () {
  54790. // Check
  54791. if (!this._effect || !this._effect.isReady())
  54792. return null;
  54793. // States
  54794. this._engine.enableEffect(this._effect);
  54795. this._engine.setState(false);
  54796. this._engine.setDepthBuffer(false);
  54797. this._engine.setDepthWrite(false);
  54798. // Alpha
  54799. this._engine.setAlphaMode(this.alphaMode);
  54800. if (this.alphaConstants) {
  54801. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  54802. }
  54803. // Texture
  54804. var source;
  54805. if (this._shareOutputWithPostProcess) {
  54806. source = this._shareOutputWithPostProcess.outputTexture;
  54807. }
  54808. else if (this._forcedOutputTexture) {
  54809. source = this._forcedOutputTexture;
  54810. }
  54811. else {
  54812. source = this.outputTexture;
  54813. }
  54814. this._effect._bindTexture("textureSampler", source);
  54815. // Parameters
  54816. this._effect.setVector2("scale", this._scaleRatio);
  54817. this.onApplyObservable.notifyObservers(this._effect);
  54818. return this._effect;
  54819. };
  54820. PostProcess.prototype._disposeTextures = function () {
  54821. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  54822. return;
  54823. }
  54824. if (this._textures.length > 0) {
  54825. for (var i = 0; i < this._textures.length; i++) {
  54826. this._engine._releaseTexture(this._textures.data[i]);
  54827. }
  54828. }
  54829. this._textures.dispose();
  54830. };
  54831. PostProcess.prototype.dispose = function (camera) {
  54832. camera = camera || this._camera;
  54833. this._disposeTextures();
  54834. if (this._scene) {
  54835. var index_1 = this._scene.postProcesses.indexOf(this);
  54836. if (index_1 !== -1) {
  54837. this._scene.postProcesses.splice(index_1, 1);
  54838. }
  54839. }
  54840. else {
  54841. var index_2 = this._engine.postProcesses.indexOf(this);
  54842. if (index_2 !== -1) {
  54843. this._engine.postProcesses.splice(index_2, 1);
  54844. }
  54845. }
  54846. if (!camera) {
  54847. return;
  54848. }
  54849. camera.detachPostProcess(this);
  54850. var index = camera._postProcesses.indexOf(this);
  54851. if (index === 0 && camera._postProcesses.length > 0) {
  54852. this._camera._postProcesses[0].markTextureDirty();
  54853. }
  54854. this.onActivateObservable.clear();
  54855. this.onAfterRenderObservable.clear();
  54856. this.onApplyObservable.clear();
  54857. this.onBeforeRenderObservable.clear();
  54858. this.onSizeChangedObservable.clear();
  54859. };
  54860. return PostProcess;
  54861. }());
  54862. BABYLON.PostProcess = PostProcess;
  54863. })(BABYLON || (BABYLON = {}));
  54864. //# sourceMappingURL=babylon.postProcess.js.map
  54865. var BABYLON;
  54866. (function (BABYLON) {
  54867. var PassPostProcess = /** @class */ (function (_super) {
  54868. __extends(PassPostProcess, _super);
  54869. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54870. if (camera === void 0) { camera = null; }
  54871. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54872. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  54873. }
  54874. return PassPostProcess;
  54875. }(BABYLON.PostProcess));
  54876. BABYLON.PassPostProcess = PassPostProcess;
  54877. })(BABYLON || (BABYLON = {}));
  54878. //# sourceMappingURL=babylon.passPostProcess.js.map
  54879. var __assign = (this && this.__assign) || Object.assign || function(t) {
  54880. for (var s, i = 1, n = arguments.length; i < n; i++) {
  54881. s = arguments[i];
  54882. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  54883. t[p] = s[p];
  54884. }
  54885. return t;
  54886. };
  54887. var BABYLON;
  54888. (function (BABYLON) {
  54889. var ShadowGenerator = /** @class */ (function () {
  54890. /**
  54891. * Creates a ShadowGenerator object.
  54892. * A ShadowGenerator is the required tool to use the shadows.
  54893. * Each light casting shadows needs to use its own ShadowGenerator.
  54894. * Required parameters :
  54895. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  54896. * - `light`: the light object generating the shadows.
  54897. * - `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.
  54898. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  54899. */
  54900. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  54901. // Members
  54902. this._bias = 0.00005;
  54903. this._blurBoxOffset = 1;
  54904. this._blurScale = 2;
  54905. this._blurKernel = 1;
  54906. this._useKernelBlur = false;
  54907. this._filter = ShadowGenerator.FILTER_NONE;
  54908. this._darkness = 0;
  54909. this._transparencyShadow = false;
  54910. /**
  54911. * Controls the extent to which the shadows fade out at the edge of the frustum
  54912. * Used only by directionals and spots
  54913. */
  54914. this.frustumEdgeFalloff = 0;
  54915. this.forceBackFacesOnly = false;
  54916. this._lightDirection = BABYLON.Vector3.Zero();
  54917. this._viewMatrix = BABYLON.Matrix.Zero();
  54918. this._projectionMatrix = BABYLON.Matrix.Zero();
  54919. this._transformMatrix = BABYLON.Matrix.Zero();
  54920. this._currentFaceIndex = 0;
  54921. this._currentFaceIndexCache = 0;
  54922. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  54923. this._mapSize = mapSize;
  54924. this._light = light;
  54925. this._scene = light.getScene();
  54926. light._shadowGenerator = this;
  54927. // Texture type fallback from float to int if not supported.
  54928. var caps = this._scene.getEngine().getCaps();
  54929. if (!useFullFloatFirst) {
  54930. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  54931. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54932. }
  54933. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  54934. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  54935. }
  54936. else {
  54937. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  54938. }
  54939. }
  54940. else {
  54941. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  54942. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  54943. }
  54944. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  54945. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54946. }
  54947. else {
  54948. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  54949. }
  54950. }
  54951. this._initializeGenerator();
  54952. }
  54953. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  54954. // Static
  54955. get: function () {
  54956. return ShadowGenerator._FILTER_NONE;
  54957. },
  54958. enumerable: true,
  54959. configurable: true
  54960. });
  54961. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  54962. get: function () {
  54963. return ShadowGenerator._FILTER_POISSONSAMPLING;
  54964. },
  54965. enumerable: true,
  54966. configurable: true
  54967. });
  54968. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  54969. get: function () {
  54970. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  54971. },
  54972. enumerable: true,
  54973. configurable: true
  54974. });
  54975. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  54976. get: function () {
  54977. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  54978. },
  54979. enumerable: true,
  54980. configurable: true
  54981. });
  54982. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  54983. get: function () {
  54984. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  54985. },
  54986. enumerable: true,
  54987. configurable: true
  54988. });
  54989. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  54990. get: function () {
  54991. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  54992. },
  54993. enumerable: true,
  54994. configurable: true
  54995. });
  54996. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  54997. get: function () {
  54998. return this._bias;
  54999. },
  55000. set: function (bias) {
  55001. this._bias = bias;
  55002. },
  55003. enumerable: true,
  55004. configurable: true
  55005. });
  55006. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55007. get: function () {
  55008. return this._blurBoxOffset;
  55009. },
  55010. set: function (value) {
  55011. if (this._blurBoxOffset === value) {
  55012. return;
  55013. }
  55014. this._blurBoxOffset = value;
  55015. this._disposeBlurPostProcesses();
  55016. },
  55017. enumerable: true,
  55018. configurable: true
  55019. });
  55020. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55021. get: function () {
  55022. return this._blurScale;
  55023. },
  55024. set: function (value) {
  55025. if (this._blurScale === value) {
  55026. return;
  55027. }
  55028. this._blurScale = value;
  55029. this._disposeBlurPostProcesses();
  55030. },
  55031. enumerable: true,
  55032. configurable: true
  55033. });
  55034. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55035. get: function () {
  55036. return this._blurKernel;
  55037. },
  55038. set: function (value) {
  55039. if (this._blurKernel === value) {
  55040. return;
  55041. }
  55042. this._blurKernel = value;
  55043. this._disposeBlurPostProcesses();
  55044. },
  55045. enumerable: true,
  55046. configurable: true
  55047. });
  55048. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55049. get: function () {
  55050. return this._useKernelBlur;
  55051. },
  55052. set: function (value) {
  55053. if (this._useKernelBlur === value) {
  55054. return;
  55055. }
  55056. this._useKernelBlur = value;
  55057. this._disposeBlurPostProcesses();
  55058. },
  55059. enumerable: true,
  55060. configurable: true
  55061. });
  55062. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55063. get: function () {
  55064. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55065. },
  55066. set: function (value) {
  55067. this._depthScale = value;
  55068. },
  55069. enumerable: true,
  55070. configurable: true
  55071. });
  55072. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55073. get: function () {
  55074. return this._filter;
  55075. },
  55076. set: function (value) {
  55077. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55078. if (this._light.needCube()) {
  55079. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55080. this.useExponentialShadowMap = true;
  55081. return;
  55082. }
  55083. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55084. this.useCloseExponentialShadowMap = true;
  55085. return;
  55086. }
  55087. }
  55088. if (this._filter === value) {
  55089. return;
  55090. }
  55091. this._filter = value;
  55092. this._disposeBlurPostProcesses();
  55093. this._applyFilterValues();
  55094. this._light._markMeshesAsLightDirty();
  55095. },
  55096. enumerable: true,
  55097. configurable: true
  55098. });
  55099. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55100. get: function () {
  55101. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55102. },
  55103. set: function (value) {
  55104. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55105. return;
  55106. }
  55107. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55108. },
  55109. enumerable: true,
  55110. configurable: true
  55111. });
  55112. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55113. get: function () {
  55114. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55115. return this.useExponentialShadowMap;
  55116. },
  55117. set: function (value) {
  55118. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55119. this.useExponentialShadowMap = value;
  55120. },
  55121. enumerable: true,
  55122. configurable: true
  55123. });
  55124. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55125. get: function () {
  55126. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55127. return this.useBlurExponentialShadowMap;
  55128. },
  55129. set: function (value) {
  55130. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55131. this.useBlurExponentialShadowMap = value;
  55132. },
  55133. enumerable: true,
  55134. configurable: true
  55135. });
  55136. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55137. get: function () {
  55138. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55139. },
  55140. set: function (value) {
  55141. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55142. return;
  55143. }
  55144. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55145. },
  55146. enumerable: true,
  55147. configurable: true
  55148. });
  55149. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55150. get: function () {
  55151. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55152. },
  55153. set: function (value) {
  55154. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55155. return;
  55156. }
  55157. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55158. },
  55159. enumerable: true,
  55160. configurable: true
  55161. });
  55162. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55163. get: function () {
  55164. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55165. },
  55166. set: function (value) {
  55167. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55168. return;
  55169. }
  55170. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55171. },
  55172. enumerable: true,
  55173. configurable: true
  55174. });
  55175. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55176. get: function () {
  55177. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55178. },
  55179. set: function (value) {
  55180. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55181. return;
  55182. }
  55183. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55184. },
  55185. enumerable: true,
  55186. configurable: true
  55187. });
  55188. /**
  55189. * Returns the darkness value (float).
  55190. */
  55191. ShadowGenerator.prototype.getDarkness = function () {
  55192. return this._darkness;
  55193. };
  55194. /**
  55195. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55196. * Returns the ShadowGenerator.
  55197. */
  55198. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55199. if (darkness >= 1.0)
  55200. this._darkness = 1.0;
  55201. else if (darkness <= 0.0)
  55202. this._darkness = 0.0;
  55203. else
  55204. this._darkness = darkness;
  55205. return this;
  55206. };
  55207. /**
  55208. * Sets the ability to have transparent shadow (boolean).
  55209. * Returns the ShadowGenerator.
  55210. */
  55211. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55212. this._transparencyShadow = hasShadow;
  55213. return this;
  55214. };
  55215. /**
  55216. * Returns a RenderTargetTexture object : the shadow map texture.
  55217. */
  55218. ShadowGenerator.prototype.getShadowMap = function () {
  55219. return this._shadowMap;
  55220. };
  55221. /**
  55222. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55223. */
  55224. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55225. if (this._shadowMap2) {
  55226. return this._shadowMap2;
  55227. }
  55228. return this._shadowMap;
  55229. };
  55230. /**
  55231. * Helper function to add a mesh and its descendants to the list of shadow casters
  55232. * @param mesh Mesh to add
  55233. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  55234. */
  55235. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  55236. if (includeDescendants === void 0) { includeDescendants = true; }
  55237. if (!this._shadowMap) {
  55238. return this;
  55239. }
  55240. if (!this._shadowMap.renderList) {
  55241. this._shadowMap.renderList = [];
  55242. }
  55243. this._shadowMap.renderList.push(mesh);
  55244. if (includeDescendants) {
  55245. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  55246. }
  55247. return this;
  55248. var _a;
  55249. };
  55250. /**
  55251. * Helper function to remove a mesh and its descendants from the list of shadow casters
  55252. * @param mesh Mesh to remove
  55253. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  55254. */
  55255. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  55256. if (includeDescendants === void 0) { includeDescendants = true; }
  55257. if (!this._shadowMap || !this._shadowMap.renderList) {
  55258. return this;
  55259. }
  55260. var index = this._shadowMap.renderList.indexOf(mesh);
  55261. if (index !== -1) {
  55262. this._shadowMap.renderList.splice(index, 1);
  55263. }
  55264. if (includeDescendants) {
  55265. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  55266. var child = _a[_i];
  55267. this.removeShadowCaster(child);
  55268. }
  55269. }
  55270. return this;
  55271. };
  55272. /**
  55273. * Returns the associated light object.
  55274. */
  55275. ShadowGenerator.prototype.getLight = function () {
  55276. return this._light;
  55277. };
  55278. ShadowGenerator.prototype._initializeGenerator = function () {
  55279. this._light._markMeshesAsLightDirty();
  55280. this._initializeShadowMap();
  55281. };
  55282. ShadowGenerator.prototype._initializeShadowMap = function () {
  55283. var _this = this;
  55284. // Render target
  55285. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  55286. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55287. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55288. this._shadowMap.anisotropicFilteringLevel = 1;
  55289. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55290. this._shadowMap.renderParticles = false;
  55291. this._shadowMap.ignoreCameraViewport = true;
  55292. // Record Face Index before render.
  55293. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  55294. _this._currentFaceIndex = faceIndex;
  55295. });
  55296. // Custom render function.
  55297. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  55298. // Blur if required afer render.
  55299. this._shadowMap.onAfterUnbindObservable.add(function () {
  55300. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  55301. return;
  55302. }
  55303. var shadowMap = _this.getShadowMapForRendering();
  55304. if (shadowMap) {
  55305. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  55306. }
  55307. });
  55308. // Clear according to the chosen filter.
  55309. this._shadowMap.onClearObservable.add(function (engine) {
  55310. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  55311. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  55312. }
  55313. else {
  55314. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55315. }
  55316. });
  55317. };
  55318. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  55319. var _this = this;
  55320. var engine = this._scene.getEngine();
  55321. var targetSize = this._mapSize / this.blurScale;
  55322. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  55323. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  55324. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55325. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55326. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55327. }
  55328. if (this.useKernelBlur) {
  55329. 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);
  55330. this._kernelBlurXPostprocess.width = targetSize;
  55331. this._kernelBlurXPostprocess.height = targetSize;
  55332. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  55333. effect.setTexture("textureSampler", _this._shadowMap);
  55334. });
  55335. 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);
  55336. this._kernelBlurXPostprocess.autoClear = false;
  55337. this._kernelBlurYPostprocess.autoClear = false;
  55338. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55339. this._kernelBlurXPostprocess.packedFloat = true;
  55340. this._kernelBlurYPostprocess.packedFloat = true;
  55341. }
  55342. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  55343. }
  55344. else {
  55345. 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);
  55346. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  55347. effect.setFloat2("screenSize", targetSize, targetSize);
  55348. effect.setTexture("textureSampler", _this._shadowMap);
  55349. });
  55350. this._boxBlurPostprocess.autoClear = false;
  55351. this._blurPostProcesses = [this._boxBlurPostprocess];
  55352. }
  55353. };
  55354. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55355. var index;
  55356. var engine = this._scene.getEngine();
  55357. if (depthOnlySubMeshes.length) {
  55358. engine.setColorWrite(false);
  55359. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55360. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  55361. }
  55362. engine.setColorWrite(true);
  55363. }
  55364. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55365. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  55366. }
  55367. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55368. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  55369. }
  55370. if (this._transparencyShadow) {
  55371. for (index = 0; index < transparentSubMeshes.length; index++) {
  55372. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  55373. }
  55374. }
  55375. };
  55376. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  55377. var _this = this;
  55378. var mesh = subMesh.getRenderingMesh();
  55379. var scene = this._scene;
  55380. var engine = scene.getEngine();
  55381. var material = subMesh.getMaterial();
  55382. if (!material) {
  55383. return;
  55384. }
  55385. // Culling
  55386. engine.setState(material.backFaceCulling);
  55387. // Managing instances
  55388. var batch = mesh._getInstancesRenderList(subMesh._id);
  55389. if (batch.mustReturn) {
  55390. return;
  55391. }
  55392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  55393. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  55394. engine.enableEffect(this._effect);
  55395. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  55396. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  55397. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  55398. this._effect.setVector3("lightPosition", this.getLight().position);
  55399. if (scene.activeCamera) {
  55400. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  55401. }
  55402. // Alpha test
  55403. if (material && material.needAlphaTesting()) {
  55404. var alphaTexture = material.getAlphaTestTexture();
  55405. if (alphaTexture) {
  55406. this._effect.setTexture("diffuseSampler", alphaTexture);
  55407. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  55408. }
  55409. }
  55410. // Bones
  55411. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55412. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  55413. }
  55414. if (this.forceBackFacesOnly) {
  55415. engine.setState(true, 0, false, true);
  55416. }
  55417. // Draw
  55418. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55419. if (this.forceBackFacesOnly) {
  55420. engine.setState(true, 0, false, false);
  55421. }
  55422. }
  55423. else {
  55424. // Need to reset refresh rate of the shadowMap
  55425. if (this._shadowMap) {
  55426. this._shadowMap.resetRefreshCounter();
  55427. }
  55428. }
  55429. };
  55430. ShadowGenerator.prototype._applyFilterValues = function () {
  55431. if (!this._shadowMap) {
  55432. return;
  55433. }
  55434. if (this.filter === ShadowGenerator.FILTER_NONE) {
  55435. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  55436. }
  55437. else {
  55438. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55439. }
  55440. };
  55441. /**
  55442. * Force shader compilation including textures ready check
  55443. */
  55444. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  55445. var _this = this;
  55446. var localOptions = __assign({ useInstances: false }, options);
  55447. var shadowMap = this.getShadowMap();
  55448. if (!shadowMap) {
  55449. if (onCompiled) {
  55450. onCompiled(this);
  55451. }
  55452. return;
  55453. }
  55454. var renderList = shadowMap.renderList;
  55455. if (!renderList) {
  55456. if (onCompiled) {
  55457. onCompiled(this);
  55458. }
  55459. return;
  55460. }
  55461. var subMeshes = new Array();
  55462. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  55463. var mesh = renderList_1[_i];
  55464. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  55465. }
  55466. if (subMeshes.length === 0) {
  55467. if (onCompiled) {
  55468. onCompiled(this);
  55469. }
  55470. return;
  55471. }
  55472. var currentIndex = 0;
  55473. var checkReady = function () {
  55474. if (!_this._scene || !_this._scene.getEngine()) {
  55475. return;
  55476. }
  55477. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  55478. currentIndex++;
  55479. if (currentIndex >= subMeshes.length) {
  55480. if (onCompiled) {
  55481. onCompiled(_this);
  55482. }
  55483. return;
  55484. }
  55485. }
  55486. setTimeout(checkReady, 16);
  55487. };
  55488. checkReady();
  55489. };
  55490. /**
  55491. * Boolean : true when the ShadowGenerator is finally computed.
  55492. */
  55493. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  55494. var defines = [];
  55495. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55496. defines.push("#define FLOAT");
  55497. }
  55498. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55499. defines.push("#define ESM");
  55500. }
  55501. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55502. var mesh = subMesh.getMesh();
  55503. var material = subMesh.getMaterial();
  55504. // Alpha test
  55505. if (material && material.needAlphaTesting()) {
  55506. var alphaTexture = material.getAlphaTestTexture();
  55507. if (alphaTexture) {
  55508. defines.push("#define ALPHATEST");
  55509. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55510. attribs.push(BABYLON.VertexBuffer.UVKind);
  55511. defines.push("#define UV1");
  55512. }
  55513. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55514. if (alphaTexture.coordinatesIndex === 1) {
  55515. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55516. defines.push("#define UV2");
  55517. }
  55518. }
  55519. }
  55520. }
  55521. // Bones
  55522. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55523. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55524. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55525. if (mesh.numBoneInfluencers > 4) {
  55526. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55527. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55528. }
  55529. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55530. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55531. }
  55532. else {
  55533. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55534. }
  55535. // Instances
  55536. if (useInstances) {
  55537. defines.push("#define INSTANCES");
  55538. attribs.push("world0");
  55539. attribs.push("world1");
  55540. attribs.push("world2");
  55541. attribs.push("world3");
  55542. }
  55543. // Get correct effect
  55544. var join = defines.join("\n");
  55545. if (this._cachedDefines !== join) {
  55546. this._cachedDefines = join;
  55547. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  55548. }
  55549. if (!this._effect.isReady()) {
  55550. return false;
  55551. }
  55552. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55553. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  55554. this._initializeBlurRTTAndPostProcesses();
  55555. }
  55556. }
  55557. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  55558. return false;
  55559. }
  55560. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  55561. return false;
  55562. }
  55563. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  55564. return false;
  55565. }
  55566. return true;
  55567. };
  55568. /**
  55569. * This creates the defines related to the standard BJS materials.
  55570. */
  55571. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  55572. var scene = this._scene;
  55573. var light = this._light;
  55574. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55575. return;
  55576. }
  55577. defines["SHADOW" + lightIndex] = true;
  55578. if (this.usePoissonSampling) {
  55579. defines["SHADOWPCF" + lightIndex] = true;
  55580. }
  55581. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55582. defines["SHADOWESM" + lightIndex] = true;
  55583. }
  55584. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55585. defines["SHADOWCLOSEESM" + lightIndex] = true;
  55586. }
  55587. if (light.needCube()) {
  55588. defines["SHADOWCUBE" + lightIndex] = true;
  55589. }
  55590. };
  55591. /**
  55592. * This binds shadow lights related to the standard BJS materials.
  55593. * It implies the unifroms available on the materials are the standard BJS ones.
  55594. */
  55595. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  55596. var light = this._light;
  55597. var scene = this._scene;
  55598. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  55599. return;
  55600. }
  55601. var camera = scene.activeCamera;
  55602. if (!camera) {
  55603. return;
  55604. }
  55605. var shadowMap = this.getShadowMap();
  55606. if (!shadowMap) {
  55607. return;
  55608. }
  55609. if (!light.needCube()) {
  55610. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  55611. }
  55612. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  55613. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  55614. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  55615. };
  55616. // Methods
  55617. /**
  55618. * Returns a Matrix object : the updated transformation matrix.
  55619. */
  55620. ShadowGenerator.prototype.getTransformMatrix = function () {
  55621. var scene = this._scene;
  55622. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  55623. return this._transformMatrix;
  55624. }
  55625. this._currentRenderID = scene.getRenderId();
  55626. this._currentFaceIndexCache = this._currentFaceIndex;
  55627. var lightPosition = this._light.position;
  55628. if (this._light.computeTransformedInformation()) {
  55629. lightPosition = this._light.transformedPosition;
  55630. }
  55631. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  55632. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  55633. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  55634. }
  55635. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  55636. this._cachedPosition = lightPosition.clone();
  55637. this._cachedDirection = this._lightDirection.clone();
  55638. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  55639. var shadowMap = this.getShadowMap();
  55640. if (shadowMap) {
  55641. var renderList = shadowMap.renderList;
  55642. if (renderList) {
  55643. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  55644. }
  55645. }
  55646. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  55647. }
  55648. return this._transformMatrix;
  55649. };
  55650. ShadowGenerator.prototype.recreateShadowMap = function () {
  55651. var shadowMap = this._shadowMap;
  55652. if (!shadowMap) {
  55653. return;
  55654. }
  55655. // Track render list.
  55656. var renderList = shadowMap.renderList;
  55657. // Clean up existing data.
  55658. this._disposeRTTandPostProcesses();
  55659. // Reinitializes.
  55660. this._initializeGenerator();
  55661. // Reaffect the filter to ensure a correct fallback if necessary.
  55662. this.filter = this.filter;
  55663. // Reaffect the filter.
  55664. this._applyFilterValues();
  55665. // Reaffect Render List.
  55666. this._shadowMap.renderList = renderList;
  55667. };
  55668. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  55669. if (this._shadowMap2) {
  55670. this._shadowMap2.dispose();
  55671. this._shadowMap2 = null;
  55672. }
  55673. if (this._boxBlurPostprocess) {
  55674. this._boxBlurPostprocess.dispose();
  55675. this._boxBlurPostprocess = null;
  55676. }
  55677. if (this._kernelBlurXPostprocess) {
  55678. this._kernelBlurXPostprocess.dispose();
  55679. this._kernelBlurXPostprocess = null;
  55680. }
  55681. if (this._kernelBlurYPostprocess) {
  55682. this._kernelBlurYPostprocess.dispose();
  55683. this._kernelBlurYPostprocess = null;
  55684. }
  55685. this._blurPostProcesses = [];
  55686. };
  55687. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  55688. if (this._shadowMap) {
  55689. this._shadowMap.dispose();
  55690. this._shadowMap = null;
  55691. }
  55692. this._disposeBlurPostProcesses();
  55693. };
  55694. /**
  55695. * Disposes the ShadowGenerator.
  55696. * Returns nothing.
  55697. */
  55698. ShadowGenerator.prototype.dispose = function () {
  55699. this._disposeRTTandPostProcesses();
  55700. if (this._light) {
  55701. this._light._shadowGenerator = null;
  55702. this._light._markMeshesAsLightDirty();
  55703. }
  55704. };
  55705. /**
  55706. * Serializes the ShadowGenerator and returns a serializationObject.
  55707. */
  55708. ShadowGenerator.prototype.serialize = function () {
  55709. var serializationObject = {};
  55710. var shadowMap = this.getShadowMap();
  55711. if (!shadowMap) {
  55712. return serializationObject;
  55713. }
  55714. serializationObject.lightId = this._light.id;
  55715. serializationObject.mapSize = shadowMap.getRenderSize();
  55716. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  55717. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  55718. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55719. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  55720. serializationObject.usePoissonSampling = this.usePoissonSampling;
  55721. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  55722. serializationObject.depthScale = this.depthScale;
  55723. serializationObject.darkness = this.getDarkness();
  55724. serializationObject.blurBoxOffset = this.blurBoxOffset;
  55725. serializationObject.blurKernel = this.blurKernel;
  55726. serializationObject.blurScale = this.blurScale;
  55727. serializationObject.useKernelBlur = this.useKernelBlur;
  55728. serializationObject.transparencyShadow = this._transparencyShadow;
  55729. serializationObject.renderList = [];
  55730. if (shadowMap.renderList) {
  55731. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  55732. var mesh = shadowMap.renderList[meshIndex];
  55733. serializationObject.renderList.push(mesh.id);
  55734. }
  55735. }
  55736. return serializationObject;
  55737. };
  55738. /**
  55739. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  55740. */
  55741. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  55742. //casting to point light, as light is missing the position attr and typescript complains.
  55743. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  55744. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  55745. var shadowMap = shadowGenerator.getShadowMap();
  55746. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  55747. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  55748. meshes.forEach(function (mesh) {
  55749. if (!shadowMap) {
  55750. return;
  55751. }
  55752. if (!shadowMap.renderList) {
  55753. shadowMap.renderList = [];
  55754. }
  55755. shadowMap.renderList.push(mesh);
  55756. });
  55757. }
  55758. if (parsedShadowGenerator.usePoissonSampling) {
  55759. shadowGenerator.usePoissonSampling = true;
  55760. }
  55761. else if (parsedShadowGenerator.useExponentialShadowMap) {
  55762. shadowGenerator.useExponentialShadowMap = true;
  55763. }
  55764. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  55765. shadowGenerator.useBlurExponentialShadowMap = true;
  55766. }
  55767. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  55768. shadowGenerator.useCloseExponentialShadowMap = true;
  55769. }
  55770. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  55771. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  55772. }
  55773. else if (parsedShadowGenerator.useVarianceShadowMap) {
  55774. shadowGenerator.useExponentialShadowMap = true;
  55775. }
  55776. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  55777. shadowGenerator.useBlurExponentialShadowMap = true;
  55778. }
  55779. if (parsedShadowGenerator.depthScale) {
  55780. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  55781. }
  55782. if (parsedShadowGenerator.blurScale) {
  55783. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  55784. }
  55785. if (parsedShadowGenerator.blurBoxOffset) {
  55786. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  55787. }
  55788. if (parsedShadowGenerator.useKernelBlur) {
  55789. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  55790. }
  55791. if (parsedShadowGenerator.blurKernel) {
  55792. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  55793. }
  55794. if (parsedShadowGenerator.bias !== undefined) {
  55795. shadowGenerator.bias = parsedShadowGenerator.bias;
  55796. }
  55797. if (parsedShadowGenerator.darkness) {
  55798. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  55799. }
  55800. if (parsedShadowGenerator.transparencyShadow) {
  55801. shadowGenerator.setTransparencyShadow(true);
  55802. }
  55803. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  55804. return shadowGenerator;
  55805. };
  55806. ShadowGenerator._FILTER_NONE = 0;
  55807. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  55808. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  55809. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  55810. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  55811. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  55812. return ShadowGenerator;
  55813. }());
  55814. BABYLON.ShadowGenerator = ShadowGenerator;
  55815. })(BABYLON || (BABYLON = {}));
  55816. //# sourceMappingURL=babylon.shadowGenerator.js.map
  55817. var BABYLON;
  55818. (function (BABYLON) {
  55819. var DefaultLoadingScreen = /** @class */ (function () {
  55820. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  55821. if (_loadingText === void 0) { _loadingText = ""; }
  55822. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  55823. var _this = this;
  55824. this._renderingCanvas = _renderingCanvas;
  55825. this._loadingText = _loadingText;
  55826. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  55827. // Resize
  55828. this._resizeLoadingUI = function () {
  55829. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  55830. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  55831. if (!_this._loadingDiv) {
  55832. return;
  55833. }
  55834. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  55835. _this._loadingDiv.style.left = canvasRect.left + "px";
  55836. _this._loadingDiv.style.top = canvasRect.top + "px";
  55837. _this._loadingDiv.style.width = canvasRect.width + "px";
  55838. _this._loadingDiv.style.height = canvasRect.height + "px";
  55839. };
  55840. }
  55841. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  55842. if (this._loadingDiv) {
  55843. // Do not add a loading screen if there is already one
  55844. return;
  55845. }
  55846. this._loadingDiv = document.createElement("div");
  55847. this._loadingDiv.id = "babylonjsLoadingDiv";
  55848. this._loadingDiv.style.opacity = "0";
  55849. this._loadingDiv.style.transition = "opacity 1.5s ease";
  55850. this._loadingDiv.style.pointerEvents = "none";
  55851. // Loading text
  55852. this._loadingTextDiv = document.createElement("div");
  55853. this._loadingTextDiv.style.position = "absolute";
  55854. this._loadingTextDiv.style.left = "0";
  55855. this._loadingTextDiv.style.top = "50%";
  55856. this._loadingTextDiv.style.marginTop = "80px";
  55857. this._loadingTextDiv.style.width = "100%";
  55858. this._loadingTextDiv.style.height = "20px";
  55859. this._loadingTextDiv.style.fontFamily = "Arial";
  55860. this._loadingTextDiv.style.fontSize = "14px";
  55861. this._loadingTextDiv.style.color = "white";
  55862. this._loadingTextDiv.style.textAlign = "center";
  55863. this._loadingTextDiv.innerHTML = "Loading";
  55864. this._loadingDiv.appendChild(this._loadingTextDiv);
  55865. //set the predefined text
  55866. this._loadingTextDiv.innerHTML = this._loadingText;
  55867. // Generating keyframes
  55868. var style = document.createElement('style');
  55869. style.type = 'text/css';
  55870. 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 }";
  55871. style.innerHTML = keyFrames;
  55872. document.getElementsByTagName('head')[0].appendChild(style);
  55873. // Loading img
  55874. var imgBack = new Image();
  55875. 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";
  55876. imgBack.style.position = "absolute";
  55877. imgBack.style.left = "50%";
  55878. imgBack.style.top = "50%";
  55879. imgBack.style.marginLeft = "-60px";
  55880. imgBack.style.marginTop = "-60px";
  55881. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  55882. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  55883. imgBack.style.transformOrigin = "50% 50%";
  55884. imgBack.style.webkitTransformOrigin = "50% 50%";
  55885. this._loadingDiv.appendChild(imgBack);
  55886. this._resizeLoadingUI();
  55887. window.addEventListener("resize", this._resizeLoadingUI);
  55888. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  55889. document.body.appendChild(this._loadingDiv);
  55890. this._loadingDiv.style.opacity = "1";
  55891. };
  55892. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  55893. var _this = this;
  55894. if (!this._loadingDiv) {
  55895. return;
  55896. }
  55897. var onTransitionEnd = function () {
  55898. if (!_this._loadingDiv) {
  55899. return;
  55900. }
  55901. document.body.removeChild(_this._loadingDiv);
  55902. window.removeEventListener("resize", _this._resizeLoadingUI);
  55903. _this._loadingDiv = null;
  55904. };
  55905. this._loadingDiv.style.opacity = "0";
  55906. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  55907. };
  55908. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  55909. set: function (text) {
  55910. this._loadingText = text;
  55911. if (this._loadingTextDiv) {
  55912. this._loadingTextDiv.innerHTML = this._loadingText;
  55913. }
  55914. },
  55915. enumerable: true,
  55916. configurable: true
  55917. });
  55918. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  55919. get: function () {
  55920. return this._loadingDivBackgroundColor;
  55921. },
  55922. set: function (color) {
  55923. this._loadingDivBackgroundColor = color;
  55924. if (!this._loadingDiv) {
  55925. return;
  55926. }
  55927. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  55928. },
  55929. enumerable: true,
  55930. configurable: true
  55931. });
  55932. return DefaultLoadingScreen;
  55933. }());
  55934. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  55935. })(BABYLON || (BABYLON = {}));
  55936. //# sourceMappingURL=babylon.loadingScreen.js.map
  55937. var BABYLON;
  55938. (function (BABYLON) {
  55939. var SceneLoaderProgressEvent = /** @class */ (function () {
  55940. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  55941. this.lengthComputable = lengthComputable;
  55942. this.loaded = loaded;
  55943. this.total = total;
  55944. }
  55945. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  55946. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  55947. };
  55948. return SceneLoaderProgressEvent;
  55949. }());
  55950. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  55951. var SceneLoader = /** @class */ (function () {
  55952. function SceneLoader() {
  55953. }
  55954. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  55955. get: function () {
  55956. return 0;
  55957. },
  55958. enumerable: true,
  55959. configurable: true
  55960. });
  55961. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  55962. get: function () {
  55963. return 1;
  55964. },
  55965. enumerable: true,
  55966. configurable: true
  55967. });
  55968. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  55969. get: function () {
  55970. return 2;
  55971. },
  55972. enumerable: true,
  55973. configurable: true
  55974. });
  55975. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  55976. get: function () {
  55977. return 3;
  55978. },
  55979. enumerable: true,
  55980. configurable: true
  55981. });
  55982. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  55983. get: function () {
  55984. return SceneLoader._ForceFullSceneLoadingForIncremental;
  55985. },
  55986. set: function (value) {
  55987. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  55988. },
  55989. enumerable: true,
  55990. configurable: true
  55991. });
  55992. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  55993. get: function () {
  55994. return SceneLoader._ShowLoadingScreen;
  55995. },
  55996. set: function (value) {
  55997. SceneLoader._ShowLoadingScreen = value;
  55998. },
  55999. enumerable: true,
  56000. configurable: true
  56001. });
  56002. Object.defineProperty(SceneLoader, "loggingLevel", {
  56003. get: function () {
  56004. return SceneLoader._loggingLevel;
  56005. },
  56006. set: function (value) {
  56007. SceneLoader._loggingLevel = value;
  56008. },
  56009. enumerable: true,
  56010. configurable: true
  56011. });
  56012. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56013. get: function () {
  56014. return SceneLoader._CleanBoneMatrixWeights;
  56015. },
  56016. set: function (value) {
  56017. SceneLoader._CleanBoneMatrixWeights = value;
  56018. },
  56019. enumerable: true,
  56020. configurable: true
  56021. });
  56022. SceneLoader._getDefaultPlugin = function () {
  56023. return SceneLoader._registeredPlugins[".babylon"];
  56024. };
  56025. SceneLoader._getPluginForExtension = function (extension) {
  56026. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56027. if (registeredPlugin) {
  56028. return registeredPlugin;
  56029. }
  56030. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56031. return SceneLoader._getDefaultPlugin();
  56032. };
  56033. SceneLoader._getPluginForDirectLoad = function (data) {
  56034. for (var extension in SceneLoader._registeredPlugins) {
  56035. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56036. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56037. return SceneLoader._registeredPlugins[extension];
  56038. }
  56039. }
  56040. return SceneLoader._getDefaultPlugin();
  56041. };
  56042. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56043. if (sceneFilename.name) {
  56044. sceneFilename = sceneFilename.name;
  56045. }
  56046. var queryStringPosition = sceneFilename.indexOf("?");
  56047. if (queryStringPosition !== -1) {
  56048. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56049. }
  56050. var dotPosition = sceneFilename.lastIndexOf(".");
  56051. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56052. return SceneLoader._getPluginForExtension(extension);
  56053. };
  56054. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56055. SceneLoader._getDirectLoad = function (sceneFilename) {
  56056. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56057. return sceneFilename.substr(5);
  56058. }
  56059. return null;
  56060. };
  56061. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56062. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56063. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56064. var plugin;
  56065. if (registeredPlugin.plugin.createPlugin) {
  56066. plugin = registeredPlugin.plugin.createPlugin();
  56067. }
  56068. else {
  56069. plugin = registeredPlugin.plugin;
  56070. }
  56071. var useArrayBuffer = registeredPlugin.isBinary;
  56072. var database;
  56073. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56074. var dataCallback = function (data, responseURL) {
  56075. if (scene.isDisposed) {
  56076. onError("Scene has been disposed");
  56077. return;
  56078. }
  56079. scene.database = database;
  56080. onSuccess(plugin, data, responseURL);
  56081. };
  56082. var request = null;
  56083. var pluginDisposed = false;
  56084. var onDisposeObservable = plugin.onDisposeObservable;
  56085. if (onDisposeObservable) {
  56086. onDisposeObservable.add(function () {
  56087. pluginDisposed = true;
  56088. if (request) {
  56089. request.abort();
  56090. request = null;
  56091. }
  56092. onDispose();
  56093. });
  56094. }
  56095. var manifestChecked = function () {
  56096. if (pluginDisposed) {
  56097. return;
  56098. }
  56099. var url = rootUrl + sceneFilename;
  56100. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56101. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56102. } : undefined, database, useArrayBuffer, function (request, exception) {
  56103. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56104. });
  56105. };
  56106. if (directLoad) {
  56107. dataCallback(directLoad);
  56108. return plugin;
  56109. }
  56110. if (rootUrl.indexOf("file:") === -1) {
  56111. if (scene.getEngine().enableOfflineSupport) {
  56112. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56113. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56114. }
  56115. else {
  56116. manifestChecked();
  56117. }
  56118. }
  56119. else {
  56120. var fileOrString = sceneFilename;
  56121. if (fileOrString.name) {
  56122. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56123. }
  56124. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56125. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56126. }
  56127. else {
  56128. onError("Unable to find file named " + sceneFilename);
  56129. }
  56130. }
  56131. return plugin;
  56132. };
  56133. // Public functions
  56134. SceneLoader.GetPluginForExtension = function (extension) {
  56135. return SceneLoader._getPluginForExtension(extension).plugin;
  56136. };
  56137. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56138. return !!SceneLoader._registeredPlugins[extension];
  56139. };
  56140. SceneLoader.RegisterPlugin = function (plugin) {
  56141. if (typeof plugin.extensions === "string") {
  56142. var extension = plugin.extensions;
  56143. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56144. plugin: plugin,
  56145. isBinary: false
  56146. };
  56147. }
  56148. else {
  56149. var extensions = plugin.extensions;
  56150. Object.keys(extensions).forEach(function (extension) {
  56151. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56152. plugin: plugin,
  56153. isBinary: extensions[extension].isBinary
  56154. };
  56155. });
  56156. }
  56157. };
  56158. /**
  56159. * Import meshes into a scene
  56160. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56161. * @param rootUrl a string that defines the root url for scene and resources
  56162. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56163. * @param scene the instance of BABYLON.Scene to append to
  56164. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56165. * @param onProgress a callback with a progress event for each file being loaded
  56166. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56167. */
  56168. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56169. if (onSuccess === void 0) { onSuccess = null; }
  56170. if (onProgress === void 0) { onProgress = null; }
  56171. if (onError === void 0) { onError = null; }
  56172. if (pluginExtension === void 0) { pluginExtension = null; }
  56173. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56174. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56175. return null;
  56176. }
  56177. var loadingToken = {};
  56178. scene._addPendingData(loadingToken);
  56179. var disposeHandler = function () {
  56180. scene._removePendingData(loadingToken);
  56181. };
  56182. var errorHandler = function (message, exception) {
  56183. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56184. if (onError) {
  56185. onError(scene, errorMessage, exception);
  56186. }
  56187. else {
  56188. BABYLON.Tools.Error(errorMessage);
  56189. // should the exception be thrown?
  56190. }
  56191. disposeHandler();
  56192. };
  56193. var progressHandler = onProgress ? function (event) {
  56194. try {
  56195. onProgress(event);
  56196. }
  56197. catch (e) {
  56198. errorHandler("Error in onProgress callback", e);
  56199. }
  56200. } : undefined;
  56201. var successHandler = function (meshes, particleSystems, skeletons) {
  56202. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56203. if (onSuccess) {
  56204. try {
  56205. onSuccess(meshes, particleSystems, skeletons);
  56206. }
  56207. catch (e) {
  56208. errorHandler("Error in onSuccess callback", e);
  56209. }
  56210. }
  56211. scene._removePendingData(loadingToken);
  56212. };
  56213. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56214. if (plugin.rewriteRootURL) {
  56215. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56216. }
  56217. if (plugin.importMesh) {
  56218. var syncedPlugin = plugin;
  56219. var meshes = new Array();
  56220. var particleSystems = new Array();
  56221. var skeletons = new Array();
  56222. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56223. return;
  56224. }
  56225. scene.loadingPluginName = plugin.name;
  56226. successHandler(meshes, particleSystems, skeletons);
  56227. }
  56228. else {
  56229. var asyncedPlugin = plugin;
  56230. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56231. scene.loadingPluginName = plugin.name;
  56232. successHandler(meshes, particleSystems, skeletons);
  56233. }, progressHandler, errorHandler);
  56234. }
  56235. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56236. };
  56237. /**
  56238. * Load a scene
  56239. * @param rootUrl a string that defines the root url for scene and resources
  56240. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56241. * @param engine is the instance of BABYLON.Engine to use to create the scene
  56242. * @param onSuccess a callback with the scene when import succeeds
  56243. * @param onProgress a callback with a progress event for each file being loaded
  56244. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56245. */
  56246. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  56247. if (onSuccess === void 0) { onSuccess = null; }
  56248. if (onProgress === void 0) { onProgress = null; }
  56249. if (onError === void 0) { onError = null; }
  56250. if (pluginExtension === void 0) { pluginExtension = null; }
  56251. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  56252. };
  56253. /**
  56254. * Append a scene
  56255. * @param rootUrl a string that defines the root url for scene and resources
  56256. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56257. * @param scene is the instance of BABYLON.Scene to append to
  56258. * @param onSuccess a callback with the scene when import succeeds
  56259. * @param onProgress a callback with a progress event for each file being loaded
  56260. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56261. */
  56262. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56263. if (onSuccess === void 0) { onSuccess = null; }
  56264. if (onProgress === void 0) { onProgress = null; }
  56265. if (onError === void 0) { onError = null; }
  56266. if (pluginExtension === void 0) { pluginExtension = null; }
  56267. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56268. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56269. return null;
  56270. }
  56271. if (SceneLoader.ShowLoadingScreen) {
  56272. scene.getEngine().displayLoadingUI();
  56273. }
  56274. var loadingToken = {};
  56275. scene._addPendingData(loadingToken);
  56276. var disposeHandler = function () {
  56277. scene._removePendingData(loadingToken);
  56278. scene.getEngine().hideLoadingUI();
  56279. };
  56280. var errorHandler = function (message, exception) {
  56281. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56282. if (onError) {
  56283. onError(scene, errorMessage, exception);
  56284. }
  56285. else {
  56286. BABYLON.Tools.Error(errorMessage);
  56287. // should the exception be thrown?
  56288. }
  56289. disposeHandler();
  56290. };
  56291. var progressHandler = onProgress ? function (event) {
  56292. try {
  56293. onProgress(event);
  56294. }
  56295. catch (e) {
  56296. errorHandler("Error in onProgress callback", e);
  56297. }
  56298. } : undefined;
  56299. var successHandler = function () {
  56300. if (onSuccess) {
  56301. try {
  56302. onSuccess(scene);
  56303. }
  56304. catch (e) {
  56305. errorHandler("Error in onSuccess callback", e);
  56306. }
  56307. }
  56308. scene._removePendingData(loadingToken);
  56309. };
  56310. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56311. if (plugin.load) {
  56312. var syncedPlugin = plugin;
  56313. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  56314. return;
  56315. }
  56316. scene.loadingPluginName = plugin.name;
  56317. successHandler();
  56318. }
  56319. else {
  56320. var asyncedPlugin = plugin;
  56321. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  56322. scene.loadingPluginName = plugin.name;
  56323. successHandler();
  56324. }, progressHandler, errorHandler);
  56325. }
  56326. if (SceneLoader.ShowLoadingScreen) {
  56327. scene.executeWhenReady(function () {
  56328. scene.getEngine().hideLoadingUI();
  56329. });
  56330. }
  56331. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56332. };
  56333. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56334. if (onSuccess === void 0) { onSuccess = null; }
  56335. if (onProgress === void 0) { onProgress = null; }
  56336. if (onError === void 0) { onError = null; }
  56337. if (pluginExtension === void 0) { pluginExtension = null; }
  56338. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56339. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56340. return null;
  56341. }
  56342. var loadingToken = {};
  56343. scene._addPendingData(loadingToken);
  56344. var disposeHandler = function () {
  56345. scene._removePendingData(loadingToken);
  56346. };
  56347. var errorHandler = function (message, exception) {
  56348. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56349. if (onError) {
  56350. onError(scene, errorMessage, exception);
  56351. }
  56352. else {
  56353. BABYLON.Tools.Error(errorMessage);
  56354. // should the exception be thrown?
  56355. }
  56356. disposeHandler();
  56357. };
  56358. var progressHandler = onProgress ? function (event) {
  56359. try {
  56360. onProgress(event);
  56361. }
  56362. catch (e) {
  56363. errorHandler("Error in onProgress callback", e);
  56364. }
  56365. } : undefined;
  56366. var successHandler = function (assets) {
  56367. if (onSuccess) {
  56368. try {
  56369. onSuccess(assets);
  56370. }
  56371. catch (e) {
  56372. errorHandler("Error in onSuccess callback", e);
  56373. }
  56374. }
  56375. scene._removePendingData(loadingToken);
  56376. };
  56377. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56378. if (plugin.loadAssets) {
  56379. var syncedPlugin = plugin;
  56380. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  56381. if (!assetContainer) {
  56382. return;
  56383. }
  56384. scene.loadingPluginName = plugin.name;
  56385. successHandler(assetContainer);
  56386. }
  56387. else if (plugin.loadAssetsAsync) {
  56388. var asyncedPlugin = plugin;
  56389. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  56390. if (assetContainer) {
  56391. scene.loadingPluginName = plugin.name;
  56392. successHandler(assetContainer);
  56393. }
  56394. }, progressHandler, errorHandler);
  56395. }
  56396. else {
  56397. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  56398. }
  56399. if (SceneLoader.ShowLoadingScreen) {
  56400. scene.executeWhenReady(function () {
  56401. scene.getEngine().hideLoadingUI();
  56402. });
  56403. }
  56404. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56405. };
  56406. // Flags
  56407. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  56408. SceneLoader._ShowLoadingScreen = true;
  56409. SceneLoader._CleanBoneMatrixWeights = false;
  56410. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  56411. // Members
  56412. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  56413. SceneLoader._registeredPlugins = {};
  56414. return SceneLoader;
  56415. }());
  56416. BABYLON.SceneLoader = SceneLoader;
  56417. ;
  56418. })(BABYLON || (BABYLON = {}));
  56419. //# sourceMappingURL=babylon.sceneLoader.js.map
  56420. var BABYLON;
  56421. (function (BABYLON) {
  56422. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  56423. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56424. var parsedMaterial = parsedData.materials[index];
  56425. if (parsedMaterial.id === id) {
  56426. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56427. }
  56428. }
  56429. return null;
  56430. };
  56431. var isDescendantOf = function (mesh, names, hierarchyIds) {
  56432. for (var i in names) {
  56433. if (mesh.name === names[i]) {
  56434. hierarchyIds.push(mesh.id);
  56435. return true;
  56436. }
  56437. }
  56438. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  56439. hierarchyIds.push(mesh.id);
  56440. return true;
  56441. }
  56442. return false;
  56443. };
  56444. var logOperation = function (operation, producer) {
  56445. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  56446. };
  56447. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  56448. if (addToScene === void 0) { addToScene = false; }
  56449. var container = new BABYLON.AssetContainer(scene);
  56450. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56451. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56452. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56453. // and avoid problems with multiple concurrent .babylon loads.
  56454. var log = "importScene has failed JSON parse";
  56455. try {
  56456. var parsedData = JSON.parse(data);
  56457. log = "";
  56458. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56459. var index;
  56460. var cache;
  56461. // Lights
  56462. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  56463. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  56464. var parsedLight = parsedData.lights[index];
  56465. var light = BABYLON.Light.Parse(parsedLight, scene);
  56466. if (light) {
  56467. container.lights.push(light);
  56468. log += (index === 0 ? "\n\tLights:" : "");
  56469. log += "\n\t\t" + light.toString(fullDetails);
  56470. }
  56471. }
  56472. }
  56473. // Animations
  56474. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  56475. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  56476. var parsedAnimation = parsedData.animations[index];
  56477. var animation = BABYLON.Animation.Parse(parsedAnimation);
  56478. scene.animations.push(animation);
  56479. container.animations.push(animation);
  56480. log += (index === 0 ? "\n\tAnimations:" : "");
  56481. log += "\n\t\t" + animation.toString(fullDetails);
  56482. }
  56483. }
  56484. // Materials
  56485. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  56486. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56487. var parsedMaterial = parsedData.materials[index];
  56488. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56489. container.materials.push(mat);
  56490. log += (index === 0 ? "\n\tMaterials:" : "");
  56491. log += "\n\t\t" + mat.toString(fullDetails);
  56492. }
  56493. }
  56494. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56495. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  56496. var parsedMultiMaterial = parsedData.multiMaterials[index];
  56497. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56498. container.multiMaterials.push(mmat);
  56499. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  56500. log += "\n\t\t" + mmat.toString(fullDetails);
  56501. }
  56502. }
  56503. // Morph targets
  56504. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  56505. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  56506. var managerData = _a[_i];
  56507. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  56508. }
  56509. }
  56510. // Skeletons
  56511. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  56512. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  56513. var parsedSkeleton = parsedData.skeletons[index];
  56514. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  56515. container.skeletons.push(skeleton);
  56516. log += (index === 0 ? "\n\tSkeletons:" : "");
  56517. log += "\n\t\t" + skeleton.toString(fullDetails);
  56518. }
  56519. }
  56520. // Geometries
  56521. var geometries = parsedData.geometries;
  56522. if (geometries !== undefined && geometries !== null) {
  56523. var addedGeometry = new Array();
  56524. // Boxes
  56525. var boxes = geometries.boxes;
  56526. if (boxes !== undefined && boxes !== null) {
  56527. for (index = 0, cache = boxes.length; index < cache; index++) {
  56528. var parsedBox = boxes[index];
  56529. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  56530. }
  56531. }
  56532. // Spheres
  56533. var spheres = geometries.spheres;
  56534. if (spheres !== undefined && spheres !== null) {
  56535. for (index = 0, cache = spheres.length; index < cache; index++) {
  56536. var parsedSphere = spheres[index];
  56537. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  56538. }
  56539. }
  56540. // Cylinders
  56541. var cylinders = geometries.cylinders;
  56542. if (cylinders !== undefined && cylinders !== null) {
  56543. for (index = 0, cache = cylinders.length; index < cache; index++) {
  56544. var parsedCylinder = cylinders[index];
  56545. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  56546. }
  56547. }
  56548. // Toruses
  56549. var toruses = geometries.toruses;
  56550. if (toruses !== undefined && toruses !== null) {
  56551. for (index = 0, cache = toruses.length; index < cache; index++) {
  56552. var parsedTorus = toruses[index];
  56553. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  56554. }
  56555. }
  56556. // Grounds
  56557. var grounds = geometries.grounds;
  56558. if (grounds !== undefined && grounds !== null) {
  56559. for (index = 0, cache = grounds.length; index < cache; index++) {
  56560. var parsedGround = grounds[index];
  56561. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  56562. }
  56563. }
  56564. // Planes
  56565. var planes = geometries.planes;
  56566. if (planes !== undefined && planes !== null) {
  56567. for (index = 0, cache = planes.length; index < cache; index++) {
  56568. var parsedPlane = planes[index];
  56569. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  56570. }
  56571. }
  56572. // TorusKnots
  56573. var torusKnots = geometries.torusKnots;
  56574. if (torusKnots !== undefined && torusKnots !== null) {
  56575. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  56576. var parsedTorusKnot = torusKnots[index];
  56577. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  56578. }
  56579. }
  56580. // VertexData
  56581. var vertexData = geometries.vertexData;
  56582. if (vertexData !== undefined && vertexData !== null) {
  56583. for (index = 0, cache = vertexData.length; index < cache; index++) {
  56584. var parsedVertexData = vertexData[index];
  56585. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  56586. }
  56587. }
  56588. addedGeometry.forEach(function (g) {
  56589. if (g) {
  56590. container.geometries.push(g);
  56591. }
  56592. });
  56593. }
  56594. // Transform nodes
  56595. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  56596. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  56597. var parsedTransformNode = parsedData.transformNodes[index];
  56598. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  56599. container.transformNodes.push(node);
  56600. }
  56601. }
  56602. // Meshes
  56603. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56604. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56605. var parsedMesh = parsedData.meshes[index];
  56606. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  56607. container.meshes.push(mesh);
  56608. log += (index === 0 ? "\n\tMeshes:" : "");
  56609. log += "\n\t\t" + mesh.toString(fullDetails);
  56610. }
  56611. }
  56612. // Cameras
  56613. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  56614. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  56615. var parsedCamera = parsedData.cameras[index];
  56616. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  56617. container.cameras.push(camera);
  56618. log += (index === 0 ? "\n\tCameras:" : "");
  56619. log += "\n\t\t" + camera.toString(fullDetails);
  56620. }
  56621. }
  56622. // Browsing all the graph to connect the dots
  56623. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  56624. var camera = scene.cameras[index];
  56625. if (camera._waitingParentId) {
  56626. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  56627. camera._waitingParentId = null;
  56628. }
  56629. }
  56630. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56631. var light_1 = scene.lights[index];
  56632. if (light_1 && light_1._waitingParentId) {
  56633. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  56634. light_1._waitingParentId = null;
  56635. }
  56636. }
  56637. // Sounds
  56638. // TODO: add sound
  56639. var loadedSounds = [];
  56640. var loadedSound;
  56641. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  56642. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  56643. var parsedSound = parsedData.sounds[index];
  56644. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56645. if (!parsedSound.url)
  56646. parsedSound.url = parsedSound.name;
  56647. if (!loadedSounds[parsedSound.url]) {
  56648. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  56649. loadedSounds[parsedSound.url] = loadedSound;
  56650. container.sounds.push(loadedSound);
  56651. }
  56652. else {
  56653. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  56654. }
  56655. }
  56656. else {
  56657. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  56658. }
  56659. }
  56660. }
  56661. loadedSounds = [];
  56662. // Connect parents & children and parse actions
  56663. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  56664. var transformNode = scene.transformNodes[index];
  56665. if (transformNode._waitingParentId) {
  56666. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  56667. transformNode._waitingParentId = null;
  56668. }
  56669. }
  56670. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56671. var mesh = scene.meshes[index];
  56672. if (mesh._waitingParentId) {
  56673. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  56674. mesh._waitingParentId = null;
  56675. }
  56676. if (mesh._waitingActions) {
  56677. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  56678. mesh._waitingActions = null;
  56679. }
  56680. }
  56681. // freeze world matrix application
  56682. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56683. var currentMesh = scene.meshes[index];
  56684. if (currentMesh._waitingFreezeWorldMatrix) {
  56685. currentMesh.freezeWorldMatrix();
  56686. currentMesh._waitingFreezeWorldMatrix = null;
  56687. }
  56688. else {
  56689. currentMesh.computeWorldMatrix(true);
  56690. }
  56691. }
  56692. // Particles Systems
  56693. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56694. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56695. var parsedParticleSystem = parsedData.particleSystems[index];
  56696. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  56697. container.particleSystems.push(ps);
  56698. }
  56699. }
  56700. // Lens flares
  56701. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  56702. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  56703. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  56704. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  56705. container.lensFlareSystems.push(lf);
  56706. }
  56707. }
  56708. // Shadows
  56709. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  56710. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  56711. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  56712. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  56713. container.shadowGenerators.push(sg);
  56714. }
  56715. }
  56716. // Lights exclusions / inclusions
  56717. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  56718. var light_2 = scene.lights[index];
  56719. // Excluded check
  56720. if (light_2._excludedMeshesIds.length > 0) {
  56721. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  56722. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  56723. if (excludedMesh) {
  56724. light_2.excludedMeshes.push(excludedMesh);
  56725. }
  56726. }
  56727. light_2._excludedMeshesIds = [];
  56728. }
  56729. // Included check
  56730. if (light_2._includedOnlyMeshesIds.length > 0) {
  56731. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  56732. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  56733. if (includedOnlyMesh) {
  56734. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  56735. }
  56736. }
  56737. light_2._includedOnlyMeshesIds = [];
  56738. }
  56739. }
  56740. // Actions (scene)
  56741. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  56742. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  56743. }
  56744. if (!addToScene) {
  56745. container.removeAllFromScene();
  56746. }
  56747. return container;
  56748. }
  56749. catch (err) {
  56750. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  56751. if (onError) {
  56752. onError(msg, err);
  56753. }
  56754. else {
  56755. BABYLON.Tools.Log(msg);
  56756. throw err;
  56757. }
  56758. }
  56759. finally {
  56760. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  56761. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  56762. }
  56763. }
  56764. return null;
  56765. };
  56766. BABYLON.SceneLoader.RegisterPlugin({
  56767. name: "babylon.js",
  56768. extensions: ".babylon",
  56769. canDirectLoad: function (data) {
  56770. if (data.indexOf("babylon") !== -1) {
  56771. return true;
  56772. }
  56773. return false;
  56774. },
  56775. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  56776. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56777. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56778. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56779. // and avoid problems with multiple concurrent .babylon loads.
  56780. var log = "importMesh has failed JSON parse";
  56781. try {
  56782. var parsedData = JSON.parse(data);
  56783. log = "";
  56784. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56785. if (!meshesNames) {
  56786. meshesNames = null;
  56787. }
  56788. else if (!Array.isArray(meshesNames)) {
  56789. meshesNames = [meshesNames];
  56790. }
  56791. var hierarchyIds = new Array();
  56792. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  56793. var loadedSkeletonsIds = [];
  56794. var loadedMaterialsIds = [];
  56795. var index;
  56796. var cache;
  56797. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  56798. var parsedMesh = parsedData.meshes[index];
  56799. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  56800. if (meshesNames !== null) {
  56801. // Remove found mesh name from list.
  56802. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  56803. }
  56804. //Geometry?
  56805. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  56806. //does the file contain geometries?
  56807. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  56808. //find the correct geometry and add it to the scene
  56809. var found = false;
  56810. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  56811. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  56812. return;
  56813. }
  56814. else {
  56815. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  56816. if (parsedGeometryData.id === parsedMesh.geometryId) {
  56817. switch (geometryType) {
  56818. case "boxes":
  56819. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  56820. break;
  56821. case "spheres":
  56822. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  56823. break;
  56824. case "cylinders":
  56825. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  56826. break;
  56827. case "toruses":
  56828. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  56829. break;
  56830. case "grounds":
  56831. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  56832. break;
  56833. case "planes":
  56834. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  56835. break;
  56836. case "torusKnots":
  56837. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  56838. break;
  56839. case "vertexData":
  56840. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  56841. break;
  56842. }
  56843. found = true;
  56844. }
  56845. });
  56846. }
  56847. });
  56848. if (found === false) {
  56849. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  56850. }
  56851. }
  56852. }
  56853. // Material ?
  56854. if (parsedMesh.materialId) {
  56855. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  56856. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56857. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  56858. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  56859. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  56860. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  56861. var subMatId = parsedMultiMaterial.materials[matIndex];
  56862. loadedMaterialsIds.push(subMatId);
  56863. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  56864. log += "\n\tMaterial " + mat.toString(fullDetails);
  56865. }
  56866. loadedMaterialsIds.push(parsedMultiMaterial.id);
  56867. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56868. materialFound = true;
  56869. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  56870. break;
  56871. }
  56872. }
  56873. }
  56874. if (materialFound === false) {
  56875. loadedMaterialsIds.push(parsedMesh.materialId);
  56876. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  56877. if (!mat) {
  56878. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  56879. }
  56880. else {
  56881. log += "\n\tMaterial " + mat.toString(fullDetails);
  56882. }
  56883. }
  56884. }
  56885. // Skeleton ?
  56886. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  56887. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  56888. if (skeletonAlreadyLoaded === false) {
  56889. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  56890. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  56891. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  56892. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  56893. skeletons.push(skeleton);
  56894. loadedSkeletonsIds.push(parsedSkeleton.id);
  56895. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  56896. }
  56897. }
  56898. }
  56899. }
  56900. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  56901. meshes.push(mesh);
  56902. log += "\n\tMesh " + mesh.toString(fullDetails);
  56903. }
  56904. }
  56905. // Connecting parents
  56906. var currentMesh;
  56907. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56908. currentMesh = scene.meshes[index];
  56909. if (currentMesh._waitingParentId) {
  56910. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  56911. currentMesh._waitingParentId = null;
  56912. }
  56913. }
  56914. // freeze and compute world matrix application
  56915. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  56916. currentMesh = scene.meshes[index];
  56917. if (currentMesh._waitingFreezeWorldMatrix) {
  56918. currentMesh.freezeWorldMatrix();
  56919. currentMesh._waitingFreezeWorldMatrix = null;
  56920. }
  56921. else {
  56922. currentMesh.computeWorldMatrix(true);
  56923. }
  56924. }
  56925. }
  56926. // Particles
  56927. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  56928. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  56929. var parsedParticleSystem = parsedData.particleSystems[index];
  56930. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  56931. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  56932. }
  56933. }
  56934. }
  56935. return true;
  56936. }
  56937. catch (err) {
  56938. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  56939. if (onError) {
  56940. onError(msg, err);
  56941. }
  56942. else {
  56943. BABYLON.Tools.Log(msg);
  56944. throw err;
  56945. }
  56946. }
  56947. finally {
  56948. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  56949. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  56950. }
  56951. }
  56952. return false;
  56953. },
  56954. load: function (scene, data, rootUrl, onError) {
  56955. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56956. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56957. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56958. // and avoid problems with multiple concurrent .babylon loads.
  56959. var log = "importScene has failed JSON parse";
  56960. try {
  56961. var parsedData = JSON.parse(data);
  56962. log = "";
  56963. // Scene
  56964. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  56965. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  56966. }
  56967. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  56968. scene.autoClear = parsedData.autoClear;
  56969. }
  56970. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  56971. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  56972. }
  56973. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  56974. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  56975. }
  56976. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  56977. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  56978. }
  56979. // Fog
  56980. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  56981. scene.fogMode = parsedData.fogMode;
  56982. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  56983. scene.fogStart = parsedData.fogStart;
  56984. scene.fogEnd = parsedData.fogEnd;
  56985. scene.fogDensity = parsedData.fogDensity;
  56986. log += "\tFog mode for scene: ";
  56987. switch (scene.fogMode) {
  56988. // getters not compiling, so using hardcoded
  56989. case 1:
  56990. log += "exp\n";
  56991. break;
  56992. case 2:
  56993. log += "exp2\n";
  56994. break;
  56995. case 3:
  56996. log += "linear\n";
  56997. break;
  56998. }
  56999. }
  57000. //Physics
  57001. if (parsedData.physicsEnabled) {
  57002. var physicsPlugin;
  57003. if (parsedData.physicsEngine === "cannon") {
  57004. physicsPlugin = new BABYLON.CannonJSPlugin();
  57005. }
  57006. else if (parsedData.physicsEngine === "oimo") {
  57007. physicsPlugin = new BABYLON.OimoJSPlugin();
  57008. }
  57009. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57010. //else - default engine, which is currently oimo
  57011. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57012. scene.enablePhysics(physicsGravity, physicsPlugin);
  57013. }
  57014. // Metadata
  57015. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57016. scene.metadata = parsedData.metadata;
  57017. }
  57018. //collisions, if defined. otherwise, default is true
  57019. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57020. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57021. }
  57022. scene.workerCollisions = !!parsedData.workerCollisions;
  57023. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57024. if (!container) {
  57025. return false;
  57026. }
  57027. if (parsedData.autoAnimate) {
  57028. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57029. }
  57030. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57031. scene.setActiveCameraByID(parsedData.activeCameraID);
  57032. }
  57033. // Environment texture
  57034. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57035. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57036. if (parsedData.createDefaultSkybox === true) {
  57037. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57038. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57039. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57040. }
  57041. }
  57042. // Finish
  57043. return true;
  57044. }
  57045. catch (err) {
  57046. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57047. if (onError) {
  57048. onError(msg, err);
  57049. }
  57050. else {
  57051. BABYLON.Tools.Log(msg);
  57052. throw err;
  57053. }
  57054. }
  57055. finally {
  57056. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57057. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57058. }
  57059. }
  57060. return false;
  57061. },
  57062. loadAssets: function (scene, data, rootUrl, onError) {
  57063. var container = loadAssets(scene, data, rootUrl, onerror);
  57064. return container;
  57065. }
  57066. });
  57067. })(BABYLON || (BABYLON = {}));
  57068. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57069. var BABYLON;
  57070. (function (BABYLON) {
  57071. var FilesInput = /** @class */ (function () {
  57072. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57073. this.onProcessFileCallback = function () { return true; };
  57074. this._engine = engine;
  57075. this._currentScene = scene;
  57076. this._sceneLoadedCallback = sceneLoadedCallback;
  57077. this._progressCallback = progressCallback;
  57078. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57079. this._textureLoadingCallback = textureLoadingCallback;
  57080. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57081. this._onReloadCallback = onReloadCallback;
  57082. this._errorCallback = errorCallback;
  57083. }
  57084. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57085. var _this = this;
  57086. if (elementToMonitor) {
  57087. this._elementToMonitor = elementToMonitor;
  57088. this._dragEnterHandler = function (e) { _this.drag(e); };
  57089. this._dragOverHandler = function (e) { _this.drag(e); };
  57090. this._dropHandler = function (e) { _this.drop(e); };
  57091. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57092. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57093. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57094. }
  57095. };
  57096. FilesInput.prototype.dispose = function () {
  57097. if (!this._elementToMonitor) {
  57098. return;
  57099. }
  57100. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57101. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57102. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57103. };
  57104. FilesInput.prototype.renderFunction = function () {
  57105. if (this._additionalRenderLoopLogicCallback) {
  57106. this._additionalRenderLoopLogicCallback();
  57107. }
  57108. if (this._currentScene) {
  57109. if (this._textureLoadingCallback) {
  57110. var remaining = this._currentScene.getWaitingItemsCount();
  57111. if (remaining > 0) {
  57112. this._textureLoadingCallback(remaining);
  57113. }
  57114. }
  57115. this._currentScene.render();
  57116. }
  57117. };
  57118. FilesInput.prototype.drag = function (e) {
  57119. e.stopPropagation();
  57120. e.preventDefault();
  57121. };
  57122. FilesInput.prototype.drop = function (eventDrop) {
  57123. eventDrop.stopPropagation();
  57124. eventDrop.preventDefault();
  57125. this.loadFiles(eventDrop);
  57126. };
  57127. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57128. var _this = this;
  57129. var reader = folder.createReader();
  57130. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57131. reader.readEntries(function (entries) {
  57132. remaining.count += entries.length;
  57133. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57134. var entry = entries_1[_i];
  57135. if (entry.isFile) {
  57136. entry.file(function (file) {
  57137. file.correctName = relativePath + file.name;
  57138. files.push(file);
  57139. if (--remaining.count === 0) {
  57140. callback();
  57141. }
  57142. });
  57143. }
  57144. else if (entry.isDirectory) {
  57145. _this._traverseFolder(entry, files, remaining, callback);
  57146. }
  57147. }
  57148. if (--remaining.count) {
  57149. callback();
  57150. }
  57151. });
  57152. };
  57153. FilesInput.prototype._processFiles = function (files) {
  57154. for (var i = 0; i < files.length; i++) {
  57155. var name = files[i].correctName.toLowerCase();
  57156. var extension = name.split('.').pop();
  57157. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57158. continue;
  57159. }
  57160. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57161. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57162. this._sceneFileToLoad = files[i];
  57163. }
  57164. else {
  57165. FilesInput.FilesToLoad[name] = files[i];
  57166. }
  57167. }
  57168. };
  57169. FilesInput.prototype.loadFiles = function (event) {
  57170. var _this = this;
  57171. if (this._startingProcessingFilesCallback)
  57172. this._startingProcessingFilesCallback();
  57173. // Handling data transfer via drag'n'drop
  57174. if (event && event.dataTransfer && event.dataTransfer.files) {
  57175. this._filesToLoad = event.dataTransfer.files;
  57176. }
  57177. // Handling files from input files
  57178. if (event && event.target && event.target.files) {
  57179. this._filesToLoad = event.target.files;
  57180. }
  57181. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57182. var files_1 = new Array();
  57183. var folders = [];
  57184. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57185. for (var i = 0; i < this._filesToLoad.length; i++) {
  57186. var fileToLoad = this._filesToLoad[i];
  57187. var name_1 = fileToLoad.name.toLowerCase();
  57188. var entry = void 0;
  57189. fileToLoad.correctName = name_1;
  57190. if (items) {
  57191. var item = items[i];
  57192. if (item.getAsEntry) {
  57193. entry = item.getAsEntry();
  57194. }
  57195. else if (item.webkitGetAsEntry) {
  57196. entry = item.webkitGetAsEntry();
  57197. }
  57198. }
  57199. if (!entry) {
  57200. files_1.push(fileToLoad);
  57201. }
  57202. else {
  57203. if (entry.isDirectory) {
  57204. folders.push(entry);
  57205. }
  57206. else {
  57207. files_1.push(fileToLoad);
  57208. }
  57209. }
  57210. }
  57211. if (folders.length === 0) {
  57212. this._processFiles(files_1);
  57213. this._processReload();
  57214. }
  57215. else {
  57216. var remaining = { count: folders.length };
  57217. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57218. var folder = folders_1[_i];
  57219. this._traverseFolder(folder, files_1, remaining, function () {
  57220. _this._processFiles(files_1);
  57221. if (remaining.count === 0) {
  57222. _this._processReload();
  57223. }
  57224. });
  57225. }
  57226. }
  57227. }
  57228. };
  57229. FilesInput.prototype._processReload = function () {
  57230. if (this._onReloadCallback) {
  57231. this._onReloadCallback(this._sceneFileToLoad);
  57232. }
  57233. else {
  57234. this.reload();
  57235. }
  57236. };
  57237. FilesInput.prototype.reload = function () {
  57238. var _this = this;
  57239. // If a scene file has been provided
  57240. if (this._sceneFileToLoad) {
  57241. if (this._currentScene) {
  57242. if (BABYLON.Tools.errorsCount > 0) {
  57243. BABYLON.Tools.ClearLogCache();
  57244. }
  57245. this._engine.stopRenderLoop();
  57246. this._currentScene.dispose();
  57247. }
  57248. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  57249. _this._currentScene = newScene;
  57250. if (_this._sceneLoadedCallback) {
  57251. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  57252. }
  57253. // Wait for textures and shaders to be ready
  57254. _this._currentScene.executeWhenReady(function () {
  57255. _this._engine.runRenderLoop(function () {
  57256. _this.renderFunction();
  57257. });
  57258. });
  57259. }, function (progress) {
  57260. if (_this._progressCallback) {
  57261. _this._progressCallback(progress);
  57262. }
  57263. }, function (scene, message) {
  57264. _this._currentScene = scene;
  57265. if (_this._errorCallback) {
  57266. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  57267. }
  57268. });
  57269. }
  57270. else {
  57271. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  57272. }
  57273. };
  57274. FilesInput.FilesToLoad = {};
  57275. return FilesInput;
  57276. }());
  57277. BABYLON.FilesInput = FilesInput;
  57278. })(BABYLON || (BABYLON = {}));
  57279. //# sourceMappingURL=babylon.filesInput.js.map
  57280. var BABYLON;
  57281. (function (BABYLON) {
  57282. /**
  57283. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57284. * The underlying implementation relies on an associative array to ensure the best performances.
  57285. * The value can be anything including 'null' but except 'undefined'
  57286. */
  57287. var StringDictionary = /** @class */ (function () {
  57288. function StringDictionary() {
  57289. this._count = 0;
  57290. this._data = {};
  57291. }
  57292. /**
  57293. * This will clear this dictionary and copy the content from the 'source' one.
  57294. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57295. * @param source the dictionary to take the content from and copy to this dictionary
  57296. */
  57297. StringDictionary.prototype.copyFrom = function (source) {
  57298. var _this = this;
  57299. this.clear();
  57300. source.forEach(function (t, v) { return _this.add(t, v); });
  57301. };
  57302. /**
  57303. * Get a value based from its key
  57304. * @param key the given key to get the matching value from
  57305. * @return the value if found, otherwise undefined is returned
  57306. */
  57307. StringDictionary.prototype.get = function (key) {
  57308. var val = this._data[key];
  57309. if (val !== undefined) {
  57310. return val;
  57311. }
  57312. return undefined;
  57313. };
  57314. /**
  57315. * Get a value from its key or add it if it doesn't exist.
  57316. * This method will ensure you that a given key/data will be present in the dictionary.
  57317. * @param key the given key to get the matching value from
  57318. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57319. * The factory will only be invoked if there's no data for the given key.
  57320. * @return the value corresponding to the key.
  57321. */
  57322. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57323. var val = this.get(key);
  57324. if (val !== undefined) {
  57325. return val;
  57326. }
  57327. val = factory(key);
  57328. if (val) {
  57329. this.add(key, val);
  57330. }
  57331. return val;
  57332. };
  57333. /**
  57334. * Get a value from its key if present in the dictionary otherwise add it
  57335. * @param key the key to get the value from
  57336. * @param val if there's no such key/value pair in the dictionary add it with this value
  57337. * @return the value corresponding to the key
  57338. */
  57339. StringDictionary.prototype.getOrAdd = function (key, val) {
  57340. var curVal = this.get(key);
  57341. if (curVal !== undefined) {
  57342. return curVal;
  57343. }
  57344. this.add(key, val);
  57345. return val;
  57346. };
  57347. /**
  57348. * Check if there's a given key in the dictionary
  57349. * @param key the key to check for
  57350. * @return true if the key is present, false otherwise
  57351. */
  57352. StringDictionary.prototype.contains = function (key) {
  57353. return this._data[key] !== undefined;
  57354. };
  57355. /**
  57356. * Add a new key and its corresponding value
  57357. * @param key the key to add
  57358. * @param value the value corresponding to the key
  57359. * @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
  57360. */
  57361. StringDictionary.prototype.add = function (key, value) {
  57362. if (this._data[key] !== undefined) {
  57363. return false;
  57364. }
  57365. this._data[key] = value;
  57366. ++this._count;
  57367. return true;
  57368. };
  57369. StringDictionary.prototype.set = function (key, value) {
  57370. if (this._data[key] === undefined) {
  57371. return false;
  57372. }
  57373. this._data[key] = value;
  57374. return true;
  57375. };
  57376. /**
  57377. * Get the element of the given key and remove it from the dictionary
  57378. * @param key
  57379. */
  57380. StringDictionary.prototype.getAndRemove = function (key) {
  57381. var val = this.get(key);
  57382. if (val !== undefined) {
  57383. delete this._data[key];
  57384. --this._count;
  57385. return val;
  57386. }
  57387. return null;
  57388. };
  57389. /**
  57390. * Remove a key/value from the dictionary.
  57391. * @param key the key to remove
  57392. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  57393. */
  57394. StringDictionary.prototype.remove = function (key) {
  57395. if (this.contains(key)) {
  57396. delete this._data[key];
  57397. --this._count;
  57398. return true;
  57399. }
  57400. return false;
  57401. };
  57402. /**
  57403. * Clear the whole content of the dictionary
  57404. */
  57405. StringDictionary.prototype.clear = function () {
  57406. this._data = {};
  57407. this._count = 0;
  57408. };
  57409. Object.defineProperty(StringDictionary.prototype, "count", {
  57410. get: function () {
  57411. return this._count;
  57412. },
  57413. enumerable: true,
  57414. configurable: true
  57415. });
  57416. /**
  57417. * Execute a callback on each key/val of the dictionary.
  57418. * Note that you can remove any element in this dictionary in the callback implementation
  57419. * @param callback the callback to execute on a given key/value pair
  57420. */
  57421. StringDictionary.prototype.forEach = function (callback) {
  57422. for (var cur in this._data) {
  57423. var val = this._data[cur];
  57424. callback(cur, val);
  57425. }
  57426. };
  57427. /**
  57428. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  57429. * If the callback returns null or undefined the method will iterate to the next key/value pair
  57430. * Note that you can remove any element in this dictionary in the callback implementation
  57431. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  57432. */
  57433. StringDictionary.prototype.first = function (callback) {
  57434. for (var cur in this._data) {
  57435. var val = this._data[cur];
  57436. var res = callback(cur, val);
  57437. if (res) {
  57438. return res;
  57439. }
  57440. }
  57441. return null;
  57442. };
  57443. return StringDictionary;
  57444. }());
  57445. BABYLON.StringDictionary = StringDictionary;
  57446. })(BABYLON || (BABYLON = {}));
  57447. //# sourceMappingURL=babylon.stringDictionary.js.map
  57448. var BABYLON;
  57449. (function (BABYLON) {
  57450. var Tags = /** @class */ (function () {
  57451. function Tags() {
  57452. }
  57453. Tags.EnableFor = function (obj) {
  57454. obj._tags = obj._tags || {};
  57455. obj.hasTags = function () {
  57456. return Tags.HasTags(obj);
  57457. };
  57458. obj.addTags = function (tagsString) {
  57459. return Tags.AddTagsTo(obj, tagsString);
  57460. };
  57461. obj.removeTags = function (tagsString) {
  57462. return Tags.RemoveTagsFrom(obj, tagsString);
  57463. };
  57464. obj.matchesTagsQuery = function (tagsQuery) {
  57465. return Tags.MatchesQuery(obj, tagsQuery);
  57466. };
  57467. };
  57468. Tags.DisableFor = function (obj) {
  57469. delete obj._tags;
  57470. delete obj.hasTags;
  57471. delete obj.addTags;
  57472. delete obj.removeTags;
  57473. delete obj.matchesTagsQuery;
  57474. };
  57475. Tags.HasTags = function (obj) {
  57476. if (!obj._tags) {
  57477. return false;
  57478. }
  57479. return !BABYLON.Tools.IsEmpty(obj._tags);
  57480. };
  57481. Tags.GetTags = function (obj, asString) {
  57482. if (asString === void 0) { asString = true; }
  57483. if (!obj._tags) {
  57484. return null;
  57485. }
  57486. if (asString) {
  57487. var tagsArray = [];
  57488. for (var tag in obj._tags) {
  57489. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  57490. tagsArray.push(tag);
  57491. }
  57492. }
  57493. return tagsArray.join(" ");
  57494. }
  57495. else {
  57496. return obj._tags;
  57497. }
  57498. };
  57499. // the tags 'true' and 'false' are reserved and cannot be used as tags
  57500. // a tag cannot start with '||', '&&', and '!'
  57501. // it cannot contain whitespaces
  57502. Tags.AddTagsTo = function (obj, tagsString) {
  57503. if (!tagsString) {
  57504. return;
  57505. }
  57506. if (typeof tagsString !== "string") {
  57507. return;
  57508. }
  57509. var tags = tagsString.split(" ");
  57510. tags.forEach(function (tag, index, array) {
  57511. Tags._AddTagTo(obj, tag);
  57512. });
  57513. };
  57514. Tags._AddTagTo = function (obj, tag) {
  57515. tag = tag.trim();
  57516. if (tag === "" || tag === "true" || tag === "false") {
  57517. return;
  57518. }
  57519. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  57520. return;
  57521. }
  57522. Tags.EnableFor(obj);
  57523. obj._tags[tag] = true;
  57524. };
  57525. Tags.RemoveTagsFrom = function (obj, tagsString) {
  57526. if (!Tags.HasTags(obj)) {
  57527. return;
  57528. }
  57529. var tags = tagsString.split(" ");
  57530. for (var t in tags) {
  57531. Tags._RemoveTagFrom(obj, tags[t]);
  57532. }
  57533. };
  57534. Tags._RemoveTagFrom = function (obj, tag) {
  57535. delete obj._tags[tag];
  57536. };
  57537. Tags.MatchesQuery = function (obj, tagsQuery) {
  57538. if (tagsQuery === undefined) {
  57539. return true;
  57540. }
  57541. if (tagsQuery === "") {
  57542. return Tags.HasTags(obj);
  57543. }
  57544. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  57545. };
  57546. return Tags;
  57547. }());
  57548. BABYLON.Tags = Tags;
  57549. })(BABYLON || (BABYLON = {}));
  57550. //# sourceMappingURL=babylon.tags.js.map
  57551. var BABYLON;
  57552. (function (BABYLON) {
  57553. var AndOrNotEvaluator = /** @class */ (function () {
  57554. function AndOrNotEvaluator() {
  57555. }
  57556. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  57557. if (!query.match(/\([^\(\)]*\)/g)) {
  57558. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  57559. }
  57560. else {
  57561. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  57562. // remove parenthesis
  57563. r = r.slice(1, r.length - 1);
  57564. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  57565. });
  57566. }
  57567. if (query === "true") {
  57568. return true;
  57569. }
  57570. if (query === "false") {
  57571. return false;
  57572. }
  57573. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  57574. };
  57575. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  57576. evaluateCallback = evaluateCallback || (function (r) {
  57577. return r === "true" ? true : false;
  57578. });
  57579. var result;
  57580. var or = parenthesisContent.split("||");
  57581. for (var i in or) {
  57582. if (or.hasOwnProperty(i)) {
  57583. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  57584. var and = ori.split("&&");
  57585. if (and.length > 1) {
  57586. for (var j = 0; j < and.length; ++j) {
  57587. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  57588. if (andj !== "true" && andj !== "false") {
  57589. if (andj[0] === "!") {
  57590. result = !evaluateCallback(andj.substring(1));
  57591. }
  57592. else {
  57593. result = evaluateCallback(andj);
  57594. }
  57595. }
  57596. else {
  57597. result = andj === "true" ? true : false;
  57598. }
  57599. if (!result) {
  57600. ori = "false";
  57601. break;
  57602. }
  57603. }
  57604. }
  57605. if (result || ori === "true") {
  57606. result = true;
  57607. break;
  57608. }
  57609. // result equals false (or undefined)
  57610. if (ori !== "true" && ori !== "false") {
  57611. if (ori[0] === "!") {
  57612. result = !evaluateCallback(ori.substring(1));
  57613. }
  57614. else {
  57615. result = evaluateCallback(ori);
  57616. }
  57617. }
  57618. else {
  57619. result = ori === "true" ? true : false;
  57620. }
  57621. }
  57622. }
  57623. // the whole parenthesis scope is replaced by 'true' or 'false'
  57624. return result ? "true" : "false";
  57625. };
  57626. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  57627. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  57628. // remove whitespaces
  57629. r = r.replace(/[\s]/g, function () { return ""; });
  57630. return r.length % 2 ? "!" : "";
  57631. });
  57632. booleanString = booleanString.trim();
  57633. if (booleanString === "!true") {
  57634. booleanString = "false";
  57635. }
  57636. else if (booleanString === "!false") {
  57637. booleanString = "true";
  57638. }
  57639. return booleanString;
  57640. };
  57641. return AndOrNotEvaluator;
  57642. }());
  57643. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  57644. })(BABYLON || (BABYLON = {}));
  57645. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  57646. var BABYLON;
  57647. (function (BABYLON) {
  57648. var Database = /** @class */ (function () {
  57649. function Database(urlToScene, callbackManifestChecked) {
  57650. // Handling various flavors of prefixed version of IndexedDB
  57651. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  57652. this.callbackManifestChecked = callbackManifestChecked;
  57653. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  57654. this.db = null;
  57655. this._enableSceneOffline = false;
  57656. this._enableTexturesOffline = false;
  57657. this.manifestVersionFound = 0;
  57658. this.mustUpdateRessources = false;
  57659. this.hasReachedQuota = false;
  57660. if (!Database.IDBStorageEnabled) {
  57661. this.callbackManifestChecked(true);
  57662. }
  57663. else {
  57664. this.checkManifestFile();
  57665. }
  57666. }
  57667. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  57668. get: function () {
  57669. return this._enableSceneOffline;
  57670. },
  57671. enumerable: true,
  57672. configurable: true
  57673. });
  57674. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  57675. get: function () {
  57676. return this._enableTexturesOffline;
  57677. },
  57678. enumerable: true,
  57679. configurable: true
  57680. });
  57681. Database.prototype.checkManifestFile = function () {
  57682. var _this = this;
  57683. var noManifestFile = function () {
  57684. _this._enableSceneOffline = false;
  57685. _this._enableTexturesOffline = false;
  57686. _this.callbackManifestChecked(false);
  57687. };
  57688. var timeStampUsed = false;
  57689. var manifestURL = this.currentSceneUrl + ".manifest";
  57690. var xhr = new XMLHttpRequest();
  57691. if (navigator.onLine) {
  57692. // Adding a timestamp to by-pass browsers' cache
  57693. timeStampUsed = true;
  57694. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  57695. }
  57696. xhr.open("GET", manifestURL, true);
  57697. xhr.addEventListener("load", function () {
  57698. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57699. try {
  57700. var manifestFile = JSON.parse(xhr.response);
  57701. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  57702. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  57703. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  57704. _this.manifestVersionFound = manifestFile.version;
  57705. }
  57706. if (_this.callbackManifestChecked) {
  57707. _this.callbackManifestChecked(true);
  57708. }
  57709. }
  57710. catch (ex) {
  57711. noManifestFile();
  57712. }
  57713. }
  57714. else {
  57715. noManifestFile();
  57716. }
  57717. }, false);
  57718. xhr.addEventListener("error", function (event) {
  57719. if (timeStampUsed) {
  57720. timeStampUsed = false;
  57721. // Let's retry without the timeStamp
  57722. // It could fail when coupled with HTML5 Offline API
  57723. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  57724. xhr.open("GET", retryManifestURL, true);
  57725. xhr.send();
  57726. }
  57727. else {
  57728. noManifestFile();
  57729. }
  57730. }, false);
  57731. try {
  57732. xhr.send();
  57733. }
  57734. catch (ex) {
  57735. BABYLON.Tools.Error("Error on XHR send request.");
  57736. this.callbackManifestChecked(false);
  57737. }
  57738. };
  57739. Database.prototype.openAsync = function (successCallback, errorCallback) {
  57740. var _this = this;
  57741. var handleError = function () {
  57742. _this.isSupported = false;
  57743. if (errorCallback)
  57744. errorCallback();
  57745. };
  57746. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  57747. // Your browser doesn't support IndexedDB
  57748. this.isSupported = false;
  57749. if (errorCallback)
  57750. errorCallback();
  57751. }
  57752. else {
  57753. // If the DB hasn't been opened or created yet
  57754. if (!this.db) {
  57755. this.hasReachedQuota = false;
  57756. this.isSupported = true;
  57757. var request = this.idbFactory.open("babylonjs", 1);
  57758. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  57759. request.onerror = function (event) {
  57760. handleError();
  57761. };
  57762. // executes when a version change transaction cannot complete due to other active transactions
  57763. request.onblocked = function (event) {
  57764. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  57765. handleError();
  57766. };
  57767. // DB has been opened successfully
  57768. request.onsuccess = function (event) {
  57769. _this.db = request.result;
  57770. successCallback();
  57771. };
  57772. // Initialization of the DB. Creating Scenes & Textures stores
  57773. request.onupgradeneeded = function (event) {
  57774. _this.db = (event.target).result;
  57775. if (_this.db) {
  57776. try {
  57777. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  57778. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  57779. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  57780. }
  57781. catch (ex) {
  57782. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  57783. handleError();
  57784. }
  57785. }
  57786. };
  57787. }
  57788. else {
  57789. if (successCallback)
  57790. successCallback();
  57791. }
  57792. }
  57793. };
  57794. Database.prototype.loadImageFromDB = function (url, image) {
  57795. var _this = this;
  57796. var completeURL = Database.ReturnFullUrlLocation(url);
  57797. var saveAndLoadImage = function () {
  57798. if (!_this.hasReachedQuota && _this.db !== null) {
  57799. // the texture is not yet in the DB, let's try to save it
  57800. _this._saveImageIntoDBAsync(completeURL, image);
  57801. }
  57802. else {
  57803. image.src = url;
  57804. }
  57805. };
  57806. if (!this.mustUpdateRessources) {
  57807. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  57808. }
  57809. else {
  57810. saveAndLoadImage();
  57811. }
  57812. };
  57813. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  57814. if (this.isSupported && this.db !== null) {
  57815. var texture;
  57816. var transaction = this.db.transaction(["textures"]);
  57817. transaction.onabort = function (event) {
  57818. image.src = url;
  57819. };
  57820. transaction.oncomplete = function (event) {
  57821. var blobTextureURL;
  57822. if (texture) {
  57823. var URL = window.URL || window.webkitURL;
  57824. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  57825. image.onerror = function () {
  57826. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  57827. image.src = url;
  57828. };
  57829. image.src = blobTextureURL;
  57830. }
  57831. else {
  57832. notInDBCallback();
  57833. }
  57834. };
  57835. var getRequest = transaction.objectStore("textures").get(url);
  57836. getRequest.onsuccess = function (event) {
  57837. texture = (event.target).result;
  57838. };
  57839. getRequest.onerror = function (event) {
  57840. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  57841. image.src = url;
  57842. };
  57843. }
  57844. else {
  57845. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  57846. image.src = url;
  57847. }
  57848. };
  57849. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  57850. var _this = this;
  57851. if (this.isSupported) {
  57852. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  57853. var generateBlobUrl = function () {
  57854. var blobTextureURL;
  57855. if (blob) {
  57856. var URL = window.URL || window.webkitURL;
  57857. try {
  57858. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  57859. }
  57860. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  57861. catch (ex) {
  57862. blobTextureURL = URL.createObjectURL(blob);
  57863. }
  57864. }
  57865. if (blobTextureURL) {
  57866. image.src = blobTextureURL;
  57867. }
  57868. };
  57869. if (Database.IsUASupportingBlobStorage) {
  57870. var xhr = new XMLHttpRequest(), blob;
  57871. xhr.open("GET", url, true);
  57872. xhr.responseType = "blob";
  57873. xhr.addEventListener("load", function () {
  57874. if (xhr.status === 200 && _this.db) {
  57875. // Blob as response (XHR2)
  57876. blob = xhr.response;
  57877. var transaction = _this.db.transaction(["textures"], "readwrite");
  57878. // the transaction could abort because of a QuotaExceededError error
  57879. transaction.onabort = function (event) {
  57880. try {
  57881. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  57882. var srcElement = (event.srcElement || event.target);
  57883. var error = srcElement.error;
  57884. if (error && error.name === "QuotaExceededError") {
  57885. _this.hasReachedQuota = true;
  57886. }
  57887. }
  57888. catch (ex) { }
  57889. generateBlobUrl();
  57890. };
  57891. transaction.oncomplete = function (event) {
  57892. generateBlobUrl();
  57893. };
  57894. var newTexture = { textureUrl: url, data: blob };
  57895. try {
  57896. // Put the blob into the dabase
  57897. var addRequest = transaction.objectStore("textures").put(newTexture);
  57898. addRequest.onsuccess = function (event) {
  57899. };
  57900. addRequest.onerror = function (event) {
  57901. generateBlobUrl();
  57902. };
  57903. }
  57904. catch (ex) {
  57905. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  57906. if (ex.code === 25) {
  57907. Database.IsUASupportingBlobStorage = false;
  57908. }
  57909. image.src = url;
  57910. }
  57911. }
  57912. else {
  57913. image.src = url;
  57914. }
  57915. }, false);
  57916. xhr.addEventListener("error", function (event) {
  57917. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  57918. image.src = url;
  57919. }, false);
  57920. xhr.send();
  57921. }
  57922. else {
  57923. image.src = url;
  57924. }
  57925. }
  57926. else {
  57927. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  57928. image.src = url;
  57929. }
  57930. };
  57931. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  57932. var _this = this;
  57933. var updateVersion = function () {
  57934. // the version is not yet in the DB or we need to update it
  57935. _this._saveVersionIntoDBAsync(url, versionLoaded);
  57936. };
  57937. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  57938. };
  57939. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  57940. var _this = this;
  57941. if (this.isSupported && this.db) {
  57942. var version;
  57943. try {
  57944. var transaction = this.db.transaction(["versions"]);
  57945. transaction.oncomplete = function (event) {
  57946. if (version) {
  57947. // If the version in the JSON file is > than the version in DB
  57948. if (_this.manifestVersionFound > version.data) {
  57949. _this.mustUpdateRessources = true;
  57950. updateInDBCallback();
  57951. }
  57952. else {
  57953. callback(version.data);
  57954. }
  57955. }
  57956. else {
  57957. _this.mustUpdateRessources = true;
  57958. updateInDBCallback();
  57959. }
  57960. };
  57961. transaction.onabort = function (event) {
  57962. callback(-1);
  57963. };
  57964. var getRequest = transaction.objectStore("versions").get(url);
  57965. getRequest.onsuccess = function (event) {
  57966. version = (event.target).result;
  57967. };
  57968. getRequest.onerror = function (event) {
  57969. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  57970. callback(-1);
  57971. };
  57972. }
  57973. catch (ex) {
  57974. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  57975. callback(-1);
  57976. }
  57977. }
  57978. else {
  57979. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  57980. callback(-1);
  57981. }
  57982. };
  57983. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  57984. var _this = this;
  57985. if (this.isSupported && !this.hasReachedQuota && this.db) {
  57986. try {
  57987. // Open a transaction to the database
  57988. var transaction = this.db.transaction(["versions"], "readwrite");
  57989. // the transaction could abort because of a QuotaExceededError error
  57990. transaction.onabort = function (event) {
  57991. try {
  57992. var error = event.srcElement['error'];
  57993. if (error && error.name === "QuotaExceededError") {
  57994. _this.hasReachedQuota = true;
  57995. }
  57996. }
  57997. catch (ex) { }
  57998. callback(-1);
  57999. };
  58000. transaction.oncomplete = function (event) {
  58001. callback(_this.manifestVersionFound);
  58002. };
  58003. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58004. // Put the scene into the database
  58005. var addRequest = transaction.objectStore("versions").put(newVersion);
  58006. addRequest.onsuccess = function (event) {
  58007. };
  58008. addRequest.onerror = function (event) {
  58009. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58010. };
  58011. }
  58012. catch (ex) {
  58013. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58014. callback(-1);
  58015. }
  58016. }
  58017. else {
  58018. callback(-1);
  58019. }
  58020. };
  58021. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58022. var _this = this;
  58023. var completeUrl = Database.ReturnFullUrlLocation(url);
  58024. var saveAndLoadFile = function () {
  58025. // the scene is not yet in the DB, let's try to save it
  58026. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58027. };
  58028. this._checkVersionFromDB(completeUrl, function (version) {
  58029. if (version !== -1) {
  58030. if (!_this.mustUpdateRessources) {
  58031. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58032. }
  58033. else {
  58034. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58035. }
  58036. }
  58037. else {
  58038. if (errorCallback) {
  58039. errorCallback();
  58040. }
  58041. }
  58042. });
  58043. };
  58044. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58045. if (this.isSupported && this.db) {
  58046. var targetStore;
  58047. if (url.indexOf(".babylon") !== -1) {
  58048. targetStore = "scenes";
  58049. }
  58050. else {
  58051. targetStore = "textures";
  58052. }
  58053. var file;
  58054. var transaction = this.db.transaction([targetStore]);
  58055. transaction.oncomplete = function (event) {
  58056. if (file) {
  58057. callback(file.data);
  58058. }
  58059. else {
  58060. notInDBCallback();
  58061. }
  58062. };
  58063. transaction.onabort = function (event) {
  58064. notInDBCallback();
  58065. };
  58066. var getRequest = transaction.objectStore(targetStore).get(url);
  58067. getRequest.onsuccess = function (event) {
  58068. file = (event.target).result;
  58069. };
  58070. getRequest.onerror = function (event) {
  58071. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58072. notInDBCallback();
  58073. };
  58074. }
  58075. else {
  58076. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58077. callback();
  58078. }
  58079. };
  58080. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58081. var _this = this;
  58082. if (this.isSupported) {
  58083. var targetStore;
  58084. if (url.indexOf(".babylon") !== -1) {
  58085. targetStore = "scenes";
  58086. }
  58087. else {
  58088. targetStore = "textures";
  58089. }
  58090. // Create XHR
  58091. var xhr = new XMLHttpRequest();
  58092. var fileData;
  58093. xhr.open("GET", url, true);
  58094. if (useArrayBuffer) {
  58095. xhr.responseType = "arraybuffer";
  58096. }
  58097. if (progressCallback) {
  58098. xhr.onprogress = progressCallback;
  58099. }
  58100. xhr.addEventListener("load", function () {
  58101. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58102. // Blob as response (XHR2)
  58103. //fileData = xhr.responseText;
  58104. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58105. if (!_this.hasReachedQuota && _this.db) {
  58106. // Open a transaction to the database
  58107. var transaction = _this.db.transaction([targetStore], "readwrite");
  58108. // the transaction could abort because of a QuotaExceededError error
  58109. transaction.onabort = function (event) {
  58110. try {
  58111. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58112. var error = event.srcElement['error'];
  58113. if (error && error.name === "QuotaExceededError") {
  58114. _this.hasReachedQuota = true;
  58115. }
  58116. }
  58117. catch (ex) { }
  58118. callback(fileData);
  58119. };
  58120. transaction.oncomplete = function (event) {
  58121. callback(fileData);
  58122. };
  58123. var newFile;
  58124. if (targetStore === "scenes") {
  58125. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58126. }
  58127. else {
  58128. newFile = { textureUrl: url, data: fileData };
  58129. }
  58130. try {
  58131. // Put the scene into the database
  58132. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58133. addRequest.onsuccess = function (event) {
  58134. };
  58135. addRequest.onerror = function (event) {
  58136. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58137. };
  58138. }
  58139. catch (ex) {
  58140. callback(fileData);
  58141. }
  58142. }
  58143. else {
  58144. callback(fileData);
  58145. }
  58146. }
  58147. else {
  58148. callback();
  58149. }
  58150. }, false);
  58151. xhr.addEventListener("error", function (event) {
  58152. BABYLON.Tools.Error("error on XHR request.");
  58153. callback();
  58154. }, false);
  58155. xhr.send();
  58156. }
  58157. else {
  58158. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58159. callback();
  58160. }
  58161. };
  58162. Database.IsUASupportingBlobStorage = true;
  58163. Database.IDBStorageEnabled = true;
  58164. Database.parseURL = function (url) {
  58165. var a = document.createElement('a');
  58166. a.href = url;
  58167. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58168. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58169. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58170. return absLocation;
  58171. };
  58172. Database.ReturnFullUrlLocation = function (url) {
  58173. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58174. return (Database.parseURL(window.location.href) + url);
  58175. }
  58176. else {
  58177. return url;
  58178. }
  58179. };
  58180. return Database;
  58181. }());
  58182. BABYLON.Database = Database;
  58183. })(BABYLON || (BABYLON = {}));
  58184. //# sourceMappingURL=babylon.database.js.map
  58185. var BABYLON;
  58186. (function (BABYLON) {
  58187. var FresnelParameters = /** @class */ (function () {
  58188. function FresnelParameters() {
  58189. this._isEnabled = true;
  58190. this.leftColor = BABYLON.Color3.White();
  58191. this.rightColor = BABYLON.Color3.Black();
  58192. this.bias = 0;
  58193. this.power = 1;
  58194. }
  58195. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58196. get: function () {
  58197. return this._isEnabled;
  58198. },
  58199. set: function (value) {
  58200. if (this._isEnabled === value) {
  58201. return;
  58202. }
  58203. this._isEnabled = value;
  58204. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  58205. },
  58206. enumerable: true,
  58207. configurable: true
  58208. });
  58209. FresnelParameters.prototype.clone = function () {
  58210. var newFresnelParameters = new FresnelParameters();
  58211. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58212. return newFresnelParameters;
  58213. };
  58214. FresnelParameters.prototype.serialize = function () {
  58215. var serializationObject = {};
  58216. serializationObject.isEnabled = this.isEnabled;
  58217. serializationObject.leftColor = this.leftColor;
  58218. serializationObject.rightColor = this.rightColor;
  58219. serializationObject.bias = this.bias;
  58220. serializationObject.power = this.power;
  58221. return serializationObject;
  58222. };
  58223. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58224. var fresnelParameters = new FresnelParameters();
  58225. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58226. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58227. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58228. fresnelParameters.bias = parsedFresnelParameters.bias;
  58229. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58230. return fresnelParameters;
  58231. };
  58232. return FresnelParameters;
  58233. }());
  58234. BABYLON.FresnelParameters = FresnelParameters;
  58235. })(BABYLON || (BABYLON = {}));
  58236. //# sourceMappingURL=babylon.fresnelParameters.js.map
  58237. var BABYLON;
  58238. (function (BABYLON) {
  58239. var MultiMaterial = /** @class */ (function (_super) {
  58240. __extends(MultiMaterial, _super);
  58241. function MultiMaterial(name, scene) {
  58242. var _this = _super.call(this, name, scene, true) || this;
  58243. scene.multiMaterials.push(_this);
  58244. _this.subMaterials = new Array();
  58245. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  58246. return _this;
  58247. }
  58248. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  58249. get: function () {
  58250. return this._subMaterials;
  58251. },
  58252. set: function (value) {
  58253. this._subMaterials = value;
  58254. this._hookArray(value);
  58255. },
  58256. enumerable: true,
  58257. configurable: true
  58258. });
  58259. MultiMaterial.prototype._hookArray = function (array) {
  58260. var _this = this;
  58261. var oldPush = array.push;
  58262. array.push = function () {
  58263. var items = [];
  58264. for (var _i = 0; _i < arguments.length; _i++) {
  58265. items[_i] = arguments[_i];
  58266. }
  58267. var result = oldPush.apply(array, items);
  58268. _this._markAllSubMeshesAsTexturesDirty();
  58269. return result;
  58270. };
  58271. var oldSplice = array.splice;
  58272. array.splice = function (index, deleteCount) {
  58273. var deleted = oldSplice.apply(array, [index, deleteCount]);
  58274. _this._markAllSubMeshesAsTexturesDirty();
  58275. return deleted;
  58276. };
  58277. };
  58278. // Properties
  58279. MultiMaterial.prototype.getSubMaterial = function (index) {
  58280. if (index < 0 || index >= this.subMaterials.length) {
  58281. return this.getScene().defaultMaterial;
  58282. }
  58283. return this.subMaterials[index];
  58284. };
  58285. MultiMaterial.prototype.getActiveTextures = function () {
  58286. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  58287. if (subMaterial) {
  58288. return subMaterial.getActiveTextures();
  58289. }
  58290. else {
  58291. return [];
  58292. }
  58293. }));
  58294. var _a;
  58295. };
  58296. // Methods
  58297. MultiMaterial.prototype.getClassName = function () {
  58298. return "MultiMaterial";
  58299. };
  58300. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  58301. for (var index = 0; index < this.subMaterials.length; index++) {
  58302. var subMaterial = this.subMaterials[index];
  58303. if (subMaterial) {
  58304. if (subMaterial.storeEffectOnSubMeshes) {
  58305. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  58306. return false;
  58307. }
  58308. continue;
  58309. }
  58310. if (!subMaterial.isReady(mesh)) {
  58311. return false;
  58312. }
  58313. }
  58314. }
  58315. return true;
  58316. };
  58317. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  58318. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  58319. for (var index = 0; index < this.subMaterials.length; index++) {
  58320. var subMaterial = null;
  58321. var current = this.subMaterials[index];
  58322. if (cloneChildren && current) {
  58323. subMaterial = current.clone(name + "-" + current.name);
  58324. }
  58325. else {
  58326. subMaterial = this.subMaterials[index];
  58327. }
  58328. newMultiMaterial.subMaterials.push(subMaterial);
  58329. }
  58330. return newMultiMaterial;
  58331. };
  58332. MultiMaterial.prototype.serialize = function () {
  58333. var serializationObject = {};
  58334. serializationObject.name = this.name;
  58335. serializationObject.id = this.id;
  58336. if (BABYLON.Tags) {
  58337. serializationObject.tags = BABYLON.Tags.GetTags(this);
  58338. }
  58339. serializationObject.materials = [];
  58340. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  58341. var subMat = this.subMaterials[matIndex];
  58342. if (subMat) {
  58343. serializationObject.materials.push(subMat.id);
  58344. }
  58345. else {
  58346. serializationObject.materials.push(null);
  58347. }
  58348. }
  58349. return serializationObject;
  58350. };
  58351. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58352. var scene = this.getScene();
  58353. if (!scene) {
  58354. return;
  58355. }
  58356. var index = scene.multiMaterials.indexOf(this);
  58357. if (index >= 0) {
  58358. scene.multiMaterials.splice(index, 1);
  58359. }
  58360. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58361. };
  58362. return MultiMaterial;
  58363. }(BABYLON.Material));
  58364. BABYLON.MultiMaterial = MultiMaterial;
  58365. })(BABYLON || (BABYLON = {}));
  58366. //# sourceMappingURL=babylon.multiMaterial.js.map
  58367. var BABYLON;
  58368. (function (BABYLON) {
  58369. var FreeCameraTouchInput = /** @class */ (function () {
  58370. function FreeCameraTouchInput() {
  58371. this._offsetX = null;
  58372. this._offsetY = null;
  58373. this._pointerPressed = new Array();
  58374. this.touchAngularSensibility = 200000.0;
  58375. this.touchMoveSensibility = 250.0;
  58376. }
  58377. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  58378. var _this = this;
  58379. var previousPosition = null;
  58380. if (this._pointerInput === undefined) {
  58381. this._onLostFocus = function (evt) {
  58382. _this._offsetX = null;
  58383. _this._offsetY = null;
  58384. };
  58385. this._pointerInput = function (p, s) {
  58386. var evt = p.event;
  58387. if (evt.pointerType === "mouse") {
  58388. return;
  58389. }
  58390. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  58391. if (!noPreventDefault) {
  58392. evt.preventDefault();
  58393. }
  58394. _this._pointerPressed.push(evt.pointerId);
  58395. if (_this._pointerPressed.length !== 1) {
  58396. return;
  58397. }
  58398. previousPosition = {
  58399. x: evt.clientX,
  58400. y: evt.clientY
  58401. };
  58402. }
  58403. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  58404. if (!noPreventDefault) {
  58405. evt.preventDefault();
  58406. }
  58407. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58408. if (index === -1) {
  58409. return;
  58410. }
  58411. _this._pointerPressed.splice(index, 1);
  58412. if (index != 0) {
  58413. return;
  58414. }
  58415. previousPosition = null;
  58416. _this._offsetX = null;
  58417. _this._offsetY = null;
  58418. }
  58419. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  58420. if (!noPreventDefault) {
  58421. evt.preventDefault();
  58422. }
  58423. if (!previousPosition) {
  58424. return;
  58425. }
  58426. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58427. if (index != 0) {
  58428. return;
  58429. }
  58430. _this._offsetX = evt.clientX - previousPosition.x;
  58431. _this._offsetY = -(evt.clientY - previousPosition.y);
  58432. }
  58433. };
  58434. }
  58435. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  58436. if (this._onLostFocus) {
  58437. element.addEventListener("blur", this._onLostFocus);
  58438. }
  58439. };
  58440. FreeCameraTouchInput.prototype.detachControl = function (element) {
  58441. if (this._pointerInput && element) {
  58442. if (this._observer) {
  58443. this.camera.getScene().onPointerObservable.remove(this._observer);
  58444. this._observer = null;
  58445. }
  58446. if (this._onLostFocus) {
  58447. element.removeEventListener("blur", this._onLostFocus);
  58448. this._onLostFocus = null;
  58449. }
  58450. this._pointerPressed = [];
  58451. this._offsetX = null;
  58452. this._offsetY = null;
  58453. }
  58454. };
  58455. FreeCameraTouchInput.prototype.checkInputs = function () {
  58456. if (this._offsetX && this._offsetY) {
  58457. var camera = this.camera;
  58458. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  58459. if (this._pointerPressed.length > 1) {
  58460. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  58461. }
  58462. else {
  58463. var speed = camera._computeLocalCameraSpeed();
  58464. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  58465. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  58466. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  58467. }
  58468. }
  58469. };
  58470. FreeCameraTouchInput.prototype.getClassName = function () {
  58471. return "FreeCameraTouchInput";
  58472. };
  58473. FreeCameraTouchInput.prototype.getSimpleName = function () {
  58474. return "touch";
  58475. };
  58476. __decorate([
  58477. BABYLON.serialize()
  58478. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  58479. __decorate([
  58480. BABYLON.serialize()
  58481. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  58482. return FreeCameraTouchInput;
  58483. }());
  58484. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  58485. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  58486. })(BABYLON || (BABYLON = {}));
  58487. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  58488. var BABYLON;
  58489. (function (BABYLON) {
  58490. // We're mainly based on the logic defined into the FreeCamera code
  58491. var TouchCamera = /** @class */ (function (_super) {
  58492. __extends(TouchCamera, _super);
  58493. //-- end properties for backward compatibility for inputs
  58494. function TouchCamera(name, position, scene) {
  58495. var _this = _super.call(this, name, position, scene) || this;
  58496. _this.inputs.addTouch();
  58497. _this._setupInputs();
  58498. return _this;
  58499. }
  58500. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  58501. //-- Begin properties for backward compatibility for inputs
  58502. get: function () {
  58503. var touch = this.inputs.attached["touch"];
  58504. if (touch)
  58505. return touch.touchAngularSensibility;
  58506. return 0;
  58507. },
  58508. set: function (value) {
  58509. var touch = this.inputs.attached["touch"];
  58510. if (touch)
  58511. touch.touchAngularSensibility = value;
  58512. },
  58513. enumerable: true,
  58514. configurable: true
  58515. });
  58516. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  58517. get: function () {
  58518. var touch = this.inputs.attached["touch"];
  58519. if (touch)
  58520. return touch.touchMoveSensibility;
  58521. return 0;
  58522. },
  58523. set: function (value) {
  58524. var touch = this.inputs.attached["touch"];
  58525. if (touch)
  58526. touch.touchMoveSensibility = value;
  58527. },
  58528. enumerable: true,
  58529. configurable: true
  58530. });
  58531. TouchCamera.prototype.getClassName = function () {
  58532. return "TouchCamera";
  58533. };
  58534. TouchCamera.prototype._setupInputs = function () {
  58535. var mouse = this.inputs.attached["mouse"];
  58536. if (mouse) {
  58537. mouse.touchEnabled = false;
  58538. }
  58539. };
  58540. return TouchCamera;
  58541. }(BABYLON.FreeCamera));
  58542. BABYLON.TouchCamera = TouchCamera;
  58543. })(BABYLON || (BABYLON = {}));
  58544. //# sourceMappingURL=babylon.touchCamera.js.map
  58545. var BABYLON;
  58546. (function (BABYLON) {
  58547. var ProceduralTexture = /** @class */ (function (_super) {
  58548. __extends(ProceduralTexture, _super);
  58549. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  58550. if (fallbackTexture === void 0) { fallbackTexture = null; }
  58551. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58552. if (isCube === void 0) { isCube = false; }
  58553. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58554. _this.isCube = isCube;
  58555. _this.isEnabled = true;
  58556. _this._currentRefreshId = -1;
  58557. _this._refreshRate = 1;
  58558. _this._vertexBuffers = {};
  58559. _this._uniforms = new Array();
  58560. _this._samplers = new Array();
  58561. _this._textures = {};
  58562. _this._floats = {};
  58563. _this._floatsArrays = {};
  58564. _this._colors3 = {};
  58565. _this._colors4 = {};
  58566. _this._vectors2 = {};
  58567. _this._vectors3 = {};
  58568. _this._matrices = {};
  58569. _this._fallbackTextureUsed = false;
  58570. scene._proceduralTextures.push(_this);
  58571. _this._engine = scene.getEngine();
  58572. _this.name = name;
  58573. _this.isRenderTarget = true;
  58574. _this._size = size;
  58575. _this._generateMipMaps = generateMipMaps;
  58576. _this.setFragment(fragment);
  58577. _this._fallbackTexture = fallbackTexture;
  58578. if (isCube) {
  58579. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  58580. _this.setFloat("face", 0);
  58581. }
  58582. else {
  58583. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  58584. }
  58585. // VBO
  58586. var vertices = [];
  58587. vertices.push(1, 1);
  58588. vertices.push(-1, 1);
  58589. vertices.push(-1, -1);
  58590. vertices.push(1, -1);
  58591. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  58592. _this._createIndexBuffer();
  58593. return _this;
  58594. }
  58595. ProceduralTexture.prototype._createIndexBuffer = function () {
  58596. var engine = this._engine;
  58597. // Indices
  58598. var indices = [];
  58599. indices.push(0);
  58600. indices.push(1);
  58601. indices.push(2);
  58602. indices.push(0);
  58603. indices.push(2);
  58604. indices.push(3);
  58605. this._indexBuffer = engine.createIndexBuffer(indices);
  58606. };
  58607. ProceduralTexture.prototype._rebuild = function () {
  58608. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58609. if (vb) {
  58610. vb._rebuild();
  58611. }
  58612. this._createIndexBuffer();
  58613. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  58614. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  58615. }
  58616. };
  58617. ProceduralTexture.prototype.reset = function () {
  58618. if (this._effect === undefined) {
  58619. return;
  58620. }
  58621. var engine = this._engine;
  58622. engine._releaseEffect(this._effect);
  58623. };
  58624. ProceduralTexture.prototype.isReady = function () {
  58625. var _this = this;
  58626. var engine = this._engine;
  58627. var shaders;
  58628. if (!this._fragment) {
  58629. return false;
  58630. }
  58631. if (this._fallbackTextureUsed) {
  58632. return true;
  58633. }
  58634. if (this._fragment.fragmentElement !== undefined) {
  58635. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  58636. }
  58637. else {
  58638. shaders = { vertex: "procedural", fragment: this._fragment };
  58639. }
  58640. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  58641. _this.releaseInternalTexture();
  58642. if (_this._fallbackTexture) {
  58643. _this._texture = _this._fallbackTexture._texture;
  58644. if (_this._texture) {
  58645. _this._texture.incrementReferences();
  58646. }
  58647. }
  58648. _this._fallbackTextureUsed = true;
  58649. });
  58650. return this._effect.isReady();
  58651. };
  58652. ProceduralTexture.prototype.resetRefreshCounter = function () {
  58653. this._currentRefreshId = -1;
  58654. };
  58655. ProceduralTexture.prototype.setFragment = function (fragment) {
  58656. this._fragment = fragment;
  58657. };
  58658. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  58659. get: function () {
  58660. return this._refreshRate;
  58661. },
  58662. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  58663. set: function (value) {
  58664. this._refreshRate = value;
  58665. this.resetRefreshCounter();
  58666. },
  58667. enumerable: true,
  58668. configurable: true
  58669. });
  58670. ProceduralTexture.prototype._shouldRender = function () {
  58671. if (!this.isEnabled || !this.isReady() || !this._texture) {
  58672. return false;
  58673. }
  58674. if (this._fallbackTextureUsed) {
  58675. return false;
  58676. }
  58677. if (this._currentRefreshId === -1) {
  58678. this._currentRefreshId = 1;
  58679. return true;
  58680. }
  58681. if (this.refreshRate === this._currentRefreshId) {
  58682. this._currentRefreshId = 1;
  58683. return true;
  58684. }
  58685. this._currentRefreshId++;
  58686. return false;
  58687. };
  58688. ProceduralTexture.prototype.getRenderSize = function () {
  58689. return this._size;
  58690. };
  58691. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  58692. if (this._fallbackTextureUsed) {
  58693. return;
  58694. }
  58695. this.releaseInternalTexture();
  58696. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  58697. };
  58698. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  58699. if (this._uniforms.indexOf(uniformName) === -1) {
  58700. this._uniforms.push(uniformName);
  58701. }
  58702. };
  58703. ProceduralTexture.prototype.setTexture = function (name, texture) {
  58704. if (this._samplers.indexOf(name) === -1) {
  58705. this._samplers.push(name);
  58706. }
  58707. this._textures[name] = texture;
  58708. return this;
  58709. };
  58710. ProceduralTexture.prototype.setFloat = function (name, value) {
  58711. this._checkUniform(name);
  58712. this._floats[name] = value;
  58713. return this;
  58714. };
  58715. ProceduralTexture.prototype.setFloats = function (name, value) {
  58716. this._checkUniform(name);
  58717. this._floatsArrays[name] = value;
  58718. return this;
  58719. };
  58720. ProceduralTexture.prototype.setColor3 = function (name, value) {
  58721. this._checkUniform(name);
  58722. this._colors3[name] = value;
  58723. return this;
  58724. };
  58725. ProceduralTexture.prototype.setColor4 = function (name, value) {
  58726. this._checkUniform(name);
  58727. this._colors4[name] = value;
  58728. return this;
  58729. };
  58730. ProceduralTexture.prototype.setVector2 = function (name, value) {
  58731. this._checkUniform(name);
  58732. this._vectors2[name] = value;
  58733. return this;
  58734. };
  58735. ProceduralTexture.prototype.setVector3 = function (name, value) {
  58736. this._checkUniform(name);
  58737. this._vectors3[name] = value;
  58738. return this;
  58739. };
  58740. ProceduralTexture.prototype.setMatrix = function (name, value) {
  58741. this._checkUniform(name);
  58742. this._matrices[name] = value;
  58743. return this;
  58744. };
  58745. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  58746. var scene = this.getScene();
  58747. if (!scene) {
  58748. return;
  58749. }
  58750. var engine = this._engine;
  58751. // Render
  58752. engine.enableEffect(this._effect);
  58753. engine.setState(false);
  58754. // Texture
  58755. for (var name in this._textures) {
  58756. this._effect.setTexture(name, this._textures[name]);
  58757. }
  58758. // Float
  58759. for (name in this._floats) {
  58760. this._effect.setFloat(name, this._floats[name]);
  58761. }
  58762. // Floats
  58763. for (name in this._floatsArrays) {
  58764. this._effect.setArray(name, this._floatsArrays[name]);
  58765. }
  58766. // Color3
  58767. for (name in this._colors3) {
  58768. this._effect.setColor3(name, this._colors3[name]);
  58769. }
  58770. // Color4
  58771. for (name in this._colors4) {
  58772. var color = this._colors4[name];
  58773. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58774. }
  58775. // Vector2
  58776. for (name in this._vectors2) {
  58777. this._effect.setVector2(name, this._vectors2[name]);
  58778. }
  58779. // Vector3
  58780. for (name in this._vectors3) {
  58781. this._effect.setVector3(name, this._vectors3[name]);
  58782. }
  58783. // Matrix
  58784. for (name in this._matrices) {
  58785. this._effect.setMatrix(name, this._matrices[name]);
  58786. }
  58787. if (!this._texture) {
  58788. return;
  58789. }
  58790. if (this.isCube) {
  58791. for (var face = 0; face < 6; face++) {
  58792. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  58793. // VBOs
  58794. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58795. this._effect.setFloat("face", face);
  58796. // Clear
  58797. engine.clear(scene.clearColor, true, true, true);
  58798. // Draw order
  58799. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58800. // Mipmaps
  58801. if (face === 5) {
  58802. engine.generateMipMapsForCubemap(this._texture);
  58803. }
  58804. }
  58805. }
  58806. else {
  58807. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  58808. // VBOs
  58809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  58810. // Clear
  58811. engine.clear(scene.clearColor, true, true, true);
  58812. // Draw order
  58813. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  58814. }
  58815. // Unbind
  58816. engine.unBindFramebuffer(this._texture, this.isCube);
  58817. if (this.onGenerated) {
  58818. this.onGenerated();
  58819. }
  58820. };
  58821. ProceduralTexture.prototype.clone = function () {
  58822. var textureSize = this.getSize();
  58823. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  58824. // Base texture
  58825. newTexture.hasAlpha = this.hasAlpha;
  58826. newTexture.level = this.level;
  58827. // RenderTarget Texture
  58828. newTexture.coordinatesMode = this.coordinatesMode;
  58829. return newTexture;
  58830. };
  58831. ProceduralTexture.prototype.dispose = function () {
  58832. var scene = this.getScene();
  58833. if (!scene) {
  58834. return;
  58835. }
  58836. var index = scene._proceduralTextures.indexOf(this);
  58837. if (index >= 0) {
  58838. scene._proceduralTextures.splice(index, 1);
  58839. }
  58840. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  58841. if (vertexBuffer) {
  58842. vertexBuffer.dispose();
  58843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  58844. }
  58845. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  58846. this._indexBuffer = null;
  58847. }
  58848. _super.prototype.dispose.call(this);
  58849. };
  58850. return ProceduralTexture;
  58851. }(BABYLON.Texture));
  58852. BABYLON.ProceduralTexture = ProceduralTexture;
  58853. })(BABYLON || (BABYLON = {}));
  58854. //# sourceMappingURL=babylon.proceduralTexture.js.map
  58855. var BABYLON;
  58856. (function (BABYLON) {
  58857. var CustomProceduralTexture = /** @class */ (function (_super) {
  58858. __extends(CustomProceduralTexture, _super);
  58859. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  58860. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  58861. _this._animate = true;
  58862. _this._time = 0;
  58863. _this._texturePath = texturePath;
  58864. //Try to load json
  58865. _this.loadJson(texturePath);
  58866. _this.refreshRate = 1;
  58867. return _this;
  58868. }
  58869. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  58870. var _this = this;
  58871. var noConfigFile = function () {
  58872. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  58873. try {
  58874. _this.setFragment(_this._texturePath);
  58875. }
  58876. catch (ex) {
  58877. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  58878. }
  58879. };
  58880. var configFileUrl = jsonUrl + "/config.json";
  58881. var xhr = new XMLHttpRequest();
  58882. xhr.open("GET", configFileUrl, true);
  58883. xhr.addEventListener("load", function () {
  58884. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58885. try {
  58886. _this._config = JSON.parse(xhr.response);
  58887. _this.updateShaderUniforms();
  58888. _this.updateTextures();
  58889. _this.setFragment(_this._texturePath + "/custom");
  58890. _this._animate = _this._config.animate;
  58891. _this.refreshRate = _this._config.refreshrate;
  58892. }
  58893. catch (ex) {
  58894. noConfigFile();
  58895. }
  58896. }
  58897. else {
  58898. noConfigFile();
  58899. }
  58900. }, false);
  58901. xhr.addEventListener("error", function () {
  58902. noConfigFile();
  58903. }, false);
  58904. try {
  58905. xhr.send();
  58906. }
  58907. catch (ex) {
  58908. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  58909. }
  58910. };
  58911. CustomProceduralTexture.prototype.isReady = function () {
  58912. if (!_super.prototype.isReady.call(this)) {
  58913. return false;
  58914. }
  58915. for (var name in this._textures) {
  58916. var texture = this._textures[name];
  58917. if (!texture.isReady()) {
  58918. return false;
  58919. }
  58920. }
  58921. return true;
  58922. };
  58923. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  58924. var scene = this.getScene();
  58925. if (this._animate && scene) {
  58926. this._time += scene.getAnimationRatio() * 0.03;
  58927. this.updateShaderUniforms();
  58928. }
  58929. _super.prototype.render.call(this, useCameraPostProcess);
  58930. };
  58931. CustomProceduralTexture.prototype.updateTextures = function () {
  58932. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  58933. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  58934. }
  58935. };
  58936. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  58937. if (this._config) {
  58938. for (var j = 0; j < this._config.uniforms.length; j++) {
  58939. var uniform = this._config.uniforms[j];
  58940. switch (uniform.type) {
  58941. case "float":
  58942. this.setFloat(uniform.name, uniform.value);
  58943. break;
  58944. case "color3":
  58945. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  58946. break;
  58947. case "color4":
  58948. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  58949. break;
  58950. case "vector2":
  58951. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  58952. break;
  58953. case "vector3":
  58954. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  58955. break;
  58956. }
  58957. }
  58958. }
  58959. this.setFloat("time", this._time);
  58960. };
  58961. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  58962. get: function () {
  58963. return this._animate;
  58964. },
  58965. set: function (value) {
  58966. this._animate = value;
  58967. },
  58968. enumerable: true,
  58969. configurable: true
  58970. });
  58971. return CustomProceduralTexture;
  58972. }(BABYLON.ProceduralTexture));
  58973. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  58974. })(BABYLON || (BABYLON = {}));
  58975. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  58976. var BABYLON;
  58977. (function (BABYLON) {
  58978. var FreeCameraGamepadInput = /** @class */ (function () {
  58979. function FreeCameraGamepadInput() {
  58980. this.gamepadAngularSensibility = 200;
  58981. this.gamepadMoveSensibility = 40;
  58982. // private members
  58983. this._cameraTransform = BABYLON.Matrix.Identity();
  58984. this._deltaTransform = BABYLON.Vector3.Zero();
  58985. this._vector3 = BABYLON.Vector3.Zero();
  58986. this._vector2 = BABYLON.Vector2.Zero();
  58987. }
  58988. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  58989. var _this = this;
  58990. var manager = this.camera.getScene().gamepadManager;
  58991. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  58992. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  58993. // prioritize XBOX gamepads.
  58994. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  58995. _this.gamepad = gamepad;
  58996. }
  58997. }
  58998. });
  58999. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59000. if (_this.gamepad === gamepad) {
  59001. _this.gamepad = null;
  59002. }
  59003. });
  59004. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59005. };
  59006. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59007. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59008. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59009. this.gamepad = null;
  59010. };
  59011. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59012. if (this.gamepad && this.gamepad.leftStick) {
  59013. var camera = this.camera;
  59014. var LSValues = this.gamepad.leftStick;
  59015. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59016. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59017. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59018. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59019. var RSValues = this.gamepad.rightStick;
  59020. if (RSValues) {
  59021. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59022. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59023. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59024. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59025. }
  59026. else {
  59027. RSValues = { x: 0, y: 0 };
  59028. }
  59029. if (!camera.rotationQuaternion) {
  59030. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59031. }
  59032. else {
  59033. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59034. }
  59035. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59036. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59037. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59038. camera.cameraDirection.addInPlace(this._deltaTransform);
  59039. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59040. camera.cameraRotation.addInPlace(this._vector2);
  59041. }
  59042. };
  59043. FreeCameraGamepadInput.prototype.getClassName = function () {
  59044. return "FreeCameraGamepadInput";
  59045. };
  59046. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59047. return "gamepad";
  59048. };
  59049. __decorate([
  59050. BABYLON.serialize()
  59051. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59052. __decorate([
  59053. BABYLON.serialize()
  59054. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59055. return FreeCameraGamepadInput;
  59056. }());
  59057. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59058. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59059. })(BABYLON || (BABYLON = {}));
  59060. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59061. var BABYLON;
  59062. (function (BABYLON) {
  59063. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59064. function ArcRotateCameraGamepadInput() {
  59065. this.gamepadRotationSensibility = 80;
  59066. this.gamepadMoveSensibility = 40;
  59067. }
  59068. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59069. var _this = this;
  59070. var manager = this.camera.getScene().gamepadManager;
  59071. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59072. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59073. // prioritize XBOX gamepads.
  59074. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59075. _this.gamepad = gamepad;
  59076. }
  59077. }
  59078. });
  59079. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59080. if (_this.gamepad === gamepad) {
  59081. _this.gamepad = null;
  59082. }
  59083. });
  59084. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59085. };
  59086. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59087. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59088. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59089. this.gamepad = null;
  59090. };
  59091. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59092. if (this.gamepad) {
  59093. var camera = this.camera;
  59094. var RSValues = this.gamepad.rightStick;
  59095. if (RSValues) {
  59096. if (RSValues.x != 0) {
  59097. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59098. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59099. camera.inertialAlphaOffset += normalizedRX;
  59100. }
  59101. }
  59102. if (RSValues.y != 0) {
  59103. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59104. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59105. camera.inertialBetaOffset += normalizedRY;
  59106. }
  59107. }
  59108. }
  59109. var LSValues = this.gamepad.leftStick;
  59110. if (LSValues && LSValues.y != 0) {
  59111. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59112. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59113. this.camera.inertialRadiusOffset -= normalizedLY;
  59114. }
  59115. }
  59116. }
  59117. };
  59118. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59119. return "ArcRotateCameraGamepadInput";
  59120. };
  59121. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59122. return "gamepad";
  59123. };
  59124. __decorate([
  59125. BABYLON.serialize()
  59126. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59127. __decorate([
  59128. BABYLON.serialize()
  59129. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59130. return ArcRotateCameraGamepadInput;
  59131. }());
  59132. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59133. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59134. })(BABYLON || (BABYLON = {}));
  59135. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59136. var BABYLON;
  59137. (function (BABYLON) {
  59138. var GamepadManager = /** @class */ (function () {
  59139. function GamepadManager(_scene) {
  59140. var _this = this;
  59141. this._scene = _scene;
  59142. this._babylonGamepads = [];
  59143. this._oneGamepadConnected = false;
  59144. this._isMonitoring = false;
  59145. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59146. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59147. this._gamepadEventSupported = false;
  59148. }
  59149. else {
  59150. this._gamepadEventSupported = 'GamepadEvent' in window;
  59151. this._gamepadSupport = (navigator.getGamepads ||
  59152. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59153. }
  59154. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59155. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59156. for (var i in _this._babylonGamepads) {
  59157. var gamepad = _this._babylonGamepads[i];
  59158. if (gamepad && gamepad._isConnected) {
  59159. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59160. }
  59161. }
  59162. });
  59163. this._onGamepadConnectedEvent = function (evt) {
  59164. var gamepad = evt.gamepad;
  59165. if (gamepad.index in _this._babylonGamepads) {
  59166. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59167. return;
  59168. }
  59169. }
  59170. var newGamepad;
  59171. if (_this._babylonGamepads[gamepad.index]) {
  59172. newGamepad = _this._babylonGamepads[gamepad.index];
  59173. newGamepad.browserGamepad = gamepad;
  59174. newGamepad._isConnected = true;
  59175. }
  59176. else {
  59177. newGamepad = _this._addNewGamepad(gamepad);
  59178. }
  59179. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59180. _this._startMonitoringGamepads();
  59181. };
  59182. this._onGamepadDisconnectedEvent = function (evt) {
  59183. var gamepad = evt.gamepad;
  59184. // Remove the gamepad from the list of gamepads to monitor.
  59185. for (var i in _this._babylonGamepads) {
  59186. if (_this._babylonGamepads[i].index === gamepad.index) {
  59187. var disconnectedGamepad = _this._babylonGamepads[i];
  59188. disconnectedGamepad._isConnected = false;
  59189. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59190. break;
  59191. }
  59192. }
  59193. };
  59194. if (this._gamepadSupport) {
  59195. //first add already-connected gamepads
  59196. this._updateGamepadObjects();
  59197. if (this._babylonGamepads.length) {
  59198. this._startMonitoringGamepads();
  59199. }
  59200. // Checking if the gamepad connected event is supported (like in Firefox)
  59201. if (this._gamepadEventSupported) {
  59202. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59203. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59204. }
  59205. else {
  59206. this._startMonitoringGamepads();
  59207. }
  59208. }
  59209. }
  59210. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59211. get: function () {
  59212. return this._babylonGamepads;
  59213. },
  59214. enumerable: true,
  59215. configurable: true
  59216. });
  59217. GamepadManager.prototype.getGamepadByType = function (type) {
  59218. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59219. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59220. var gamepad = _a[_i];
  59221. if (gamepad && gamepad.type === type) {
  59222. return gamepad;
  59223. }
  59224. }
  59225. return null;
  59226. };
  59227. GamepadManager.prototype.dispose = function () {
  59228. if (this._gamepadEventSupported) {
  59229. if (this._onGamepadConnectedEvent) {
  59230. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59231. }
  59232. if (this._onGamepadDisconnectedEvent) {
  59233. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  59234. }
  59235. this._onGamepadConnectedEvent = null;
  59236. this._onGamepadDisconnectedEvent = null;
  59237. }
  59238. this._babylonGamepads.forEach(function (gamepad) {
  59239. gamepad.dispose();
  59240. });
  59241. this.onGamepadConnectedObservable.clear();
  59242. this.onGamepadDisconnectedObservable.clear();
  59243. this._oneGamepadConnected = false;
  59244. this._stopMonitoringGamepads();
  59245. this._babylonGamepads = [];
  59246. };
  59247. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  59248. if (!this._oneGamepadConnected) {
  59249. this._oneGamepadConnected = true;
  59250. }
  59251. var newGamepad;
  59252. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  59253. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  59254. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  59255. }
  59256. else if (gamepad.pose) {
  59257. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  59258. }
  59259. else {
  59260. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  59261. }
  59262. this._babylonGamepads[newGamepad.index] = newGamepad;
  59263. return newGamepad;
  59264. };
  59265. GamepadManager.prototype._startMonitoringGamepads = function () {
  59266. if (!this._isMonitoring) {
  59267. this._isMonitoring = true;
  59268. //back-comp
  59269. if (!this._scene) {
  59270. this._checkGamepadsStatus();
  59271. }
  59272. }
  59273. };
  59274. GamepadManager.prototype._stopMonitoringGamepads = function () {
  59275. this._isMonitoring = false;
  59276. };
  59277. GamepadManager.prototype._checkGamepadsStatus = function () {
  59278. var _this = this;
  59279. // Hack to be compatible Chrome
  59280. this._updateGamepadObjects();
  59281. for (var i in this._babylonGamepads) {
  59282. var gamepad = this._babylonGamepads[i];
  59283. if (!gamepad || !gamepad.isConnected) {
  59284. continue;
  59285. }
  59286. gamepad.update();
  59287. }
  59288. if (this._isMonitoring && !this._scene) {
  59289. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  59290. }
  59291. };
  59292. // This function is called only on Chrome, which does not properly support
  59293. // connection/disconnection events and forces you to recopy again the gamepad object
  59294. GamepadManager.prototype._updateGamepadObjects = function () {
  59295. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  59296. for (var i = 0; i < gamepads.length; i++) {
  59297. if (gamepads[i]) {
  59298. if (!this._babylonGamepads[gamepads[i].index]) {
  59299. var newGamepad = this._addNewGamepad(gamepads[i]);
  59300. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59301. }
  59302. else {
  59303. // Forced to copy again this object for Chrome for unknown reason
  59304. this._babylonGamepads[i].browserGamepad = gamepads[i];
  59305. if (!this._babylonGamepads[i].isConnected) {
  59306. this._babylonGamepads[i]._isConnected = true;
  59307. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  59308. }
  59309. }
  59310. }
  59311. }
  59312. };
  59313. return GamepadManager;
  59314. }());
  59315. BABYLON.GamepadManager = GamepadManager;
  59316. })(BABYLON || (BABYLON = {}));
  59317. //# sourceMappingURL=babylon.gamepadManager.js.map
  59318. var BABYLON;
  59319. (function (BABYLON) {
  59320. var StickValues = /** @class */ (function () {
  59321. function StickValues(x, y) {
  59322. this.x = x;
  59323. this.y = y;
  59324. }
  59325. return StickValues;
  59326. }());
  59327. BABYLON.StickValues = StickValues;
  59328. var Gamepad = /** @class */ (function () {
  59329. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  59330. if (leftStickX === void 0) { leftStickX = 0; }
  59331. if (leftStickY === void 0) { leftStickY = 1; }
  59332. if (rightStickX === void 0) { rightStickX = 2; }
  59333. if (rightStickY === void 0) { rightStickY = 3; }
  59334. this.id = id;
  59335. this.index = index;
  59336. this.browserGamepad = browserGamepad;
  59337. this._isConnected = true;
  59338. this._invertLeftStickY = false;
  59339. this.type = Gamepad.GAMEPAD;
  59340. this._leftStickAxisX = leftStickX;
  59341. this._leftStickAxisY = leftStickY;
  59342. this._rightStickAxisX = rightStickX;
  59343. this._rightStickAxisY = rightStickY;
  59344. if (this.browserGamepad.axes.length >= 2) {
  59345. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59346. }
  59347. if (this.browserGamepad.axes.length >= 4) {
  59348. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59349. }
  59350. }
  59351. Object.defineProperty(Gamepad.prototype, "isConnected", {
  59352. get: function () {
  59353. return this._isConnected;
  59354. },
  59355. enumerable: true,
  59356. configurable: true
  59357. });
  59358. Gamepad.prototype.onleftstickchanged = function (callback) {
  59359. this._onleftstickchanged = callback;
  59360. };
  59361. Gamepad.prototype.onrightstickchanged = function (callback) {
  59362. this._onrightstickchanged = callback;
  59363. };
  59364. Object.defineProperty(Gamepad.prototype, "leftStick", {
  59365. get: function () {
  59366. return this._leftStick;
  59367. },
  59368. set: function (newValues) {
  59369. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  59370. this._onleftstickchanged(newValues);
  59371. }
  59372. this._leftStick = newValues;
  59373. },
  59374. enumerable: true,
  59375. configurable: true
  59376. });
  59377. Object.defineProperty(Gamepad.prototype, "rightStick", {
  59378. get: function () {
  59379. return this._rightStick;
  59380. },
  59381. set: function (newValues) {
  59382. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  59383. this._onrightstickchanged(newValues);
  59384. }
  59385. this._rightStick = newValues;
  59386. },
  59387. enumerable: true,
  59388. configurable: true
  59389. });
  59390. Gamepad.prototype.update = function () {
  59391. if (this._leftStick) {
  59392. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59393. if (this._invertLeftStickY) {
  59394. this.leftStick.y *= -1;
  59395. }
  59396. }
  59397. if (this._rightStick) {
  59398. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59399. }
  59400. };
  59401. Gamepad.prototype.dispose = function () {
  59402. };
  59403. Gamepad.GAMEPAD = 0;
  59404. Gamepad.GENERIC = 1;
  59405. Gamepad.XBOX = 2;
  59406. Gamepad.POSE_ENABLED = 3;
  59407. return Gamepad;
  59408. }());
  59409. BABYLON.Gamepad = Gamepad;
  59410. var GenericPad = /** @class */ (function (_super) {
  59411. __extends(GenericPad, _super);
  59412. function GenericPad(id, index, browserGamepad) {
  59413. var _this = _super.call(this, id, index, browserGamepad) || this;
  59414. _this.onButtonDownObservable = new BABYLON.Observable();
  59415. _this.onButtonUpObservable = new BABYLON.Observable();
  59416. _this.type = Gamepad.GENERIC;
  59417. _this._buttons = new Array(browserGamepad.buttons.length);
  59418. return _this;
  59419. }
  59420. GenericPad.prototype.onbuttondown = function (callback) {
  59421. this._onbuttondown = callback;
  59422. };
  59423. GenericPad.prototype.onbuttonup = function (callback) {
  59424. this._onbuttonup = callback;
  59425. };
  59426. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  59427. if (newValue !== currentValue) {
  59428. if (newValue === 1) {
  59429. if (this._onbuttondown) {
  59430. this._onbuttondown(buttonIndex);
  59431. }
  59432. this.onButtonDownObservable.notifyObservers(buttonIndex);
  59433. }
  59434. if (newValue === 0) {
  59435. if (this._onbuttonup) {
  59436. this._onbuttonup(buttonIndex);
  59437. }
  59438. this.onButtonUpObservable.notifyObservers(buttonIndex);
  59439. }
  59440. }
  59441. return newValue;
  59442. };
  59443. GenericPad.prototype.update = function () {
  59444. _super.prototype.update.call(this);
  59445. for (var index = 0; index < this._buttons.length; index++) {
  59446. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  59447. }
  59448. };
  59449. GenericPad.prototype.dispose = function () {
  59450. _super.prototype.dispose.call(this);
  59451. this.onButtonDownObservable.clear();
  59452. this.onButtonUpObservable.clear();
  59453. };
  59454. return GenericPad;
  59455. }(Gamepad));
  59456. BABYLON.GenericPad = GenericPad;
  59457. })(BABYLON || (BABYLON = {}));
  59458. //# sourceMappingURL=babylon.gamepad.js.map
  59459. var BABYLON;
  59460. (function (BABYLON) {
  59461. var Xbox360Button;
  59462. (function (Xbox360Button) {
  59463. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  59464. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  59465. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  59466. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  59467. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  59468. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  59469. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  59470. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  59471. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  59472. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  59473. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  59474. var Xbox360Dpad;
  59475. (function (Xbox360Dpad) {
  59476. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  59477. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  59478. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  59479. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  59480. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  59481. var Xbox360Pad = /** @class */ (function (_super) {
  59482. __extends(Xbox360Pad, _super);
  59483. function Xbox360Pad(id, index, gamepad, xboxOne) {
  59484. if (xboxOne === void 0) { xboxOne = false; }
  59485. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  59486. _this._leftTrigger = 0;
  59487. _this._rightTrigger = 0;
  59488. _this.onButtonDownObservable = new BABYLON.Observable();
  59489. _this.onButtonUpObservable = new BABYLON.Observable();
  59490. _this.onPadDownObservable = new BABYLON.Observable();
  59491. _this.onPadUpObservable = new BABYLON.Observable();
  59492. _this._buttonA = 0;
  59493. _this._buttonB = 0;
  59494. _this._buttonX = 0;
  59495. _this._buttonY = 0;
  59496. _this._buttonBack = 0;
  59497. _this._buttonStart = 0;
  59498. _this._buttonLB = 0;
  59499. _this._buttonRB = 0;
  59500. _this._buttonLeftStick = 0;
  59501. _this._buttonRightStick = 0;
  59502. _this._dPadUp = 0;
  59503. _this._dPadDown = 0;
  59504. _this._dPadLeft = 0;
  59505. _this._dPadRight = 0;
  59506. _this._isXboxOnePad = false;
  59507. _this.type = BABYLON.Gamepad.XBOX;
  59508. _this._isXboxOnePad = xboxOne;
  59509. return _this;
  59510. }
  59511. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  59512. this._onlefttriggerchanged = callback;
  59513. };
  59514. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  59515. this._onrighttriggerchanged = callback;
  59516. };
  59517. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  59518. get: function () {
  59519. return this._leftTrigger;
  59520. },
  59521. set: function (newValue) {
  59522. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  59523. this._onlefttriggerchanged(newValue);
  59524. }
  59525. this._leftTrigger = newValue;
  59526. },
  59527. enumerable: true,
  59528. configurable: true
  59529. });
  59530. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  59531. get: function () {
  59532. return this._rightTrigger;
  59533. },
  59534. set: function (newValue) {
  59535. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  59536. this._onrighttriggerchanged(newValue);
  59537. }
  59538. this._rightTrigger = newValue;
  59539. },
  59540. enumerable: true,
  59541. configurable: true
  59542. });
  59543. Xbox360Pad.prototype.onbuttondown = function (callback) {
  59544. this._onbuttondown = callback;
  59545. };
  59546. Xbox360Pad.prototype.onbuttonup = function (callback) {
  59547. this._onbuttonup = callback;
  59548. };
  59549. Xbox360Pad.prototype.ondpaddown = function (callback) {
  59550. this._ondpaddown = callback;
  59551. };
  59552. Xbox360Pad.prototype.ondpadup = function (callback) {
  59553. this._ondpadup = callback;
  59554. };
  59555. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  59556. if (newValue !== currentValue) {
  59557. if (newValue === 1) {
  59558. if (this._onbuttondown) {
  59559. this._onbuttondown(buttonType);
  59560. }
  59561. this.onButtonDownObservable.notifyObservers(buttonType);
  59562. }
  59563. if (newValue === 0) {
  59564. if (this._onbuttonup) {
  59565. this._onbuttonup(buttonType);
  59566. }
  59567. this.onButtonUpObservable.notifyObservers(buttonType);
  59568. }
  59569. }
  59570. return newValue;
  59571. };
  59572. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  59573. if (newValue !== currentValue) {
  59574. if (newValue === 1) {
  59575. if (this._ondpaddown) {
  59576. this._ondpaddown(buttonType);
  59577. }
  59578. this.onPadDownObservable.notifyObservers(buttonType);
  59579. }
  59580. if (newValue === 0) {
  59581. if (this._ondpadup) {
  59582. this._ondpadup(buttonType);
  59583. }
  59584. this.onPadUpObservable.notifyObservers(buttonType);
  59585. }
  59586. }
  59587. return newValue;
  59588. };
  59589. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  59590. get: function () {
  59591. return this._buttonA;
  59592. },
  59593. set: function (value) {
  59594. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  59595. },
  59596. enumerable: true,
  59597. configurable: true
  59598. });
  59599. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  59600. get: function () {
  59601. return this._buttonB;
  59602. },
  59603. set: function (value) {
  59604. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  59605. },
  59606. enumerable: true,
  59607. configurable: true
  59608. });
  59609. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  59610. get: function () {
  59611. return this._buttonX;
  59612. },
  59613. set: function (value) {
  59614. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  59615. },
  59616. enumerable: true,
  59617. configurable: true
  59618. });
  59619. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  59620. get: function () {
  59621. return this._buttonY;
  59622. },
  59623. set: function (value) {
  59624. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  59625. },
  59626. enumerable: true,
  59627. configurable: true
  59628. });
  59629. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  59630. get: function () {
  59631. return this._buttonStart;
  59632. },
  59633. set: function (value) {
  59634. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  59635. },
  59636. enumerable: true,
  59637. configurable: true
  59638. });
  59639. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  59640. get: function () {
  59641. return this._buttonBack;
  59642. },
  59643. set: function (value) {
  59644. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  59645. },
  59646. enumerable: true,
  59647. configurable: true
  59648. });
  59649. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  59650. get: function () {
  59651. return this._buttonLB;
  59652. },
  59653. set: function (value) {
  59654. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  59655. },
  59656. enumerable: true,
  59657. configurable: true
  59658. });
  59659. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  59660. get: function () {
  59661. return this._buttonRB;
  59662. },
  59663. set: function (value) {
  59664. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  59665. },
  59666. enumerable: true,
  59667. configurable: true
  59668. });
  59669. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  59670. get: function () {
  59671. return this._buttonLeftStick;
  59672. },
  59673. set: function (value) {
  59674. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  59675. },
  59676. enumerable: true,
  59677. configurable: true
  59678. });
  59679. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  59680. get: function () {
  59681. return this._buttonRightStick;
  59682. },
  59683. set: function (value) {
  59684. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  59685. },
  59686. enumerable: true,
  59687. configurable: true
  59688. });
  59689. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  59690. get: function () {
  59691. return this._dPadUp;
  59692. },
  59693. set: function (value) {
  59694. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  59695. },
  59696. enumerable: true,
  59697. configurable: true
  59698. });
  59699. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  59700. get: function () {
  59701. return this._dPadDown;
  59702. },
  59703. set: function (value) {
  59704. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  59705. },
  59706. enumerable: true,
  59707. configurable: true
  59708. });
  59709. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  59710. get: function () {
  59711. return this._dPadLeft;
  59712. },
  59713. set: function (value) {
  59714. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  59715. },
  59716. enumerable: true,
  59717. configurable: true
  59718. });
  59719. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  59720. get: function () {
  59721. return this._dPadRight;
  59722. },
  59723. set: function (value) {
  59724. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  59725. },
  59726. enumerable: true,
  59727. configurable: true
  59728. });
  59729. Xbox360Pad.prototype.update = function () {
  59730. _super.prototype.update.call(this);
  59731. if (this._isXboxOnePad) {
  59732. this.buttonA = this.browserGamepad.buttons[0].value;
  59733. this.buttonB = this.browserGamepad.buttons[1].value;
  59734. this.buttonX = this.browserGamepad.buttons[2].value;
  59735. this.buttonY = this.browserGamepad.buttons[3].value;
  59736. this.buttonLB = this.browserGamepad.buttons[4].value;
  59737. this.buttonRB = this.browserGamepad.buttons[5].value;
  59738. this.leftTrigger = this.browserGamepad.axes[2];
  59739. this.rightTrigger = this.browserGamepad.axes[5];
  59740. this.buttonBack = this.browserGamepad.buttons[9].value;
  59741. this.buttonStart = this.browserGamepad.buttons[8].value;
  59742. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  59743. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  59744. this.dPadUp = this.browserGamepad.buttons[11].value;
  59745. this.dPadDown = this.browserGamepad.buttons[12].value;
  59746. this.dPadLeft = this.browserGamepad.buttons[13].value;
  59747. this.dPadRight = this.browserGamepad.buttons[14].value;
  59748. }
  59749. else {
  59750. this.buttonA = this.browserGamepad.buttons[0].value;
  59751. this.buttonB = this.browserGamepad.buttons[1].value;
  59752. this.buttonX = this.browserGamepad.buttons[2].value;
  59753. this.buttonY = this.browserGamepad.buttons[3].value;
  59754. this.buttonLB = this.browserGamepad.buttons[4].value;
  59755. this.buttonRB = this.browserGamepad.buttons[5].value;
  59756. this.leftTrigger = this.browserGamepad.buttons[6].value;
  59757. this.rightTrigger = this.browserGamepad.buttons[7].value;
  59758. this.buttonBack = this.browserGamepad.buttons[8].value;
  59759. this.buttonStart = this.browserGamepad.buttons[9].value;
  59760. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  59761. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  59762. this.dPadUp = this.browserGamepad.buttons[12].value;
  59763. this.dPadDown = this.browserGamepad.buttons[13].value;
  59764. this.dPadLeft = this.browserGamepad.buttons[14].value;
  59765. this.dPadRight = this.browserGamepad.buttons[15].value;
  59766. }
  59767. };
  59768. Xbox360Pad.prototype.dispose = function () {
  59769. _super.prototype.dispose.call(this);
  59770. this.onButtonDownObservable.clear();
  59771. this.onButtonUpObservable.clear();
  59772. this.onPadDownObservable.clear();
  59773. this.onPadUpObservable.clear();
  59774. };
  59775. return Xbox360Pad;
  59776. }(BABYLON.Gamepad));
  59777. BABYLON.Xbox360Pad = Xbox360Pad;
  59778. })(BABYLON || (BABYLON = {}));
  59779. //# sourceMappingURL=babylon.xboxGamepad.js.map
  59780. var BABYLON;
  59781. (function (BABYLON) {
  59782. var PoseEnabledControllerType;
  59783. (function (PoseEnabledControllerType) {
  59784. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  59785. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  59786. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  59787. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  59788. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  59789. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  59790. var PoseEnabledControllerHelper = /** @class */ (function () {
  59791. function PoseEnabledControllerHelper() {
  59792. }
  59793. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  59794. // Oculus Touch
  59795. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  59796. return new BABYLON.OculusTouchController(vrGamepad);
  59797. }
  59798. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  59799. return new BABYLON.WindowsMotionController(vrGamepad);
  59800. }
  59801. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  59802. return new BABYLON.ViveController(vrGamepad);
  59803. }
  59804. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  59805. return new BABYLON.GearVRController(vrGamepad);
  59806. }
  59807. else {
  59808. return new BABYLON.GenericController(vrGamepad);
  59809. }
  59810. };
  59811. return PoseEnabledControllerHelper;
  59812. }());
  59813. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  59814. var PoseEnabledController = /** @class */ (function (_super) {
  59815. __extends(PoseEnabledController, _super);
  59816. function PoseEnabledController(browserGamepad) {
  59817. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  59818. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  59819. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  59820. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  59821. // Represents device position and rotation in babylon space
  59822. _this.devicePosition = BABYLON.Vector3.Zero();
  59823. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  59824. _this.deviceScaleFactor = 1;
  59825. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  59826. _this._deviceToWorld = BABYLON.Matrix.Identity();
  59827. _this._workingMatrix = BABYLON.Matrix.Identity();
  59828. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  59829. _this.controllerType = PoseEnabledControllerType.GENERIC;
  59830. _this.position = BABYLON.Vector3.Zero();
  59831. _this.rotationQuaternion = new BABYLON.Quaternion();
  59832. _this._calculatedPosition = BABYLON.Vector3.Zero();
  59833. _this._calculatedRotation = new BABYLON.Quaternion();
  59834. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  59835. return _this;
  59836. }
  59837. PoseEnabledController.prototype.update = function () {
  59838. _super.prototype.update.call(this);
  59839. var pose = this.browserGamepad.pose;
  59840. this.updateFromDevice(pose);
  59841. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  59842. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  59843. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  59844. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  59845. if (this._mesh) {
  59846. this._mesh.position.copyFrom(this.devicePosition);
  59847. if (this._mesh.rotationQuaternion) {
  59848. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  59849. }
  59850. }
  59851. };
  59852. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  59853. if (poseData) {
  59854. this.rawPose = poseData;
  59855. if (poseData.position) {
  59856. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  59857. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  59858. this._deviceRoomPosition.z *= -1;
  59859. }
  59860. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  59861. this._calculatedPosition.addInPlace(this.position);
  59862. }
  59863. var pose = this.rawPose;
  59864. if (poseData.orientation && pose.orientation) {
  59865. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  59866. if (this._mesh) {
  59867. if (this._mesh.getScene().useRightHandedSystem) {
  59868. this._deviceRoomRotationQuaternion.z *= -1;
  59869. this._deviceRoomRotationQuaternion.w *= -1;
  59870. }
  59871. else {
  59872. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  59873. }
  59874. }
  59875. // if the camera is set, rotate to the camera's rotation
  59876. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  59877. }
  59878. }
  59879. };
  59880. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  59881. if (this._mesh) {
  59882. this._mesh.parent = null;
  59883. }
  59884. this._mesh = mesh;
  59885. if (this._poseControlledCamera) {
  59886. this._mesh.parent = this._poseControlledCamera;
  59887. }
  59888. if (!this._mesh.rotationQuaternion) {
  59889. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  59890. }
  59891. };
  59892. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  59893. this._poseControlledCamera = camera;
  59894. if (this._mesh) {
  59895. this._mesh.parent = this._poseControlledCamera;
  59896. }
  59897. };
  59898. PoseEnabledController.prototype.dispose = function () {
  59899. if (this._mesh) {
  59900. this._mesh.dispose();
  59901. }
  59902. this._mesh = null;
  59903. _super.prototype.dispose.call(this);
  59904. };
  59905. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  59906. get: function () {
  59907. return this._mesh;
  59908. },
  59909. enumerable: true,
  59910. configurable: true
  59911. });
  59912. PoseEnabledController.prototype.getForwardRay = function (length) {
  59913. if (length === void 0) { length = 100; }
  59914. if (!this.mesh) {
  59915. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  59916. }
  59917. var m = this.mesh.getWorldMatrix();
  59918. var origin = m.getTranslation();
  59919. var forward = new BABYLON.Vector3(0, 0, -1);
  59920. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59921. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59922. return new BABYLON.Ray(origin, direction, length);
  59923. };
  59924. return PoseEnabledController;
  59925. }(BABYLON.Gamepad));
  59926. BABYLON.PoseEnabledController = PoseEnabledController;
  59927. })(BABYLON || (BABYLON = {}));
  59928. //# sourceMappingURL=babylon.poseEnabledController.js.map
  59929. var BABYLON;
  59930. (function (BABYLON) {
  59931. var WebVRController = /** @class */ (function (_super) {
  59932. __extends(WebVRController, _super);
  59933. function WebVRController(vrGamepad) {
  59934. var _this = _super.call(this, vrGamepad) || this;
  59935. // Observables
  59936. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  59937. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  59938. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  59939. _this.onPadStateChangedObservable = new BABYLON.Observable();
  59940. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  59941. _this.pad = { x: 0, y: 0 };
  59942. // avoid GC, store state in a tmp object
  59943. _this._changes = {
  59944. pressChanged: false,
  59945. touchChanged: false,
  59946. valueChanged: false,
  59947. changed: false
  59948. };
  59949. _this._buttons = new Array(vrGamepad.buttons.length);
  59950. _this.hand = vrGamepad.hand;
  59951. return _this;
  59952. }
  59953. WebVRController.prototype.onButtonStateChange = function (callback) {
  59954. this._onButtonStateChange = callback;
  59955. };
  59956. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  59957. get: function () {
  59958. return this._defaultModel;
  59959. },
  59960. enumerable: true,
  59961. configurable: true
  59962. });
  59963. WebVRController.prototype.update = function () {
  59964. _super.prototype.update.call(this);
  59965. for (var index = 0; index < this._buttons.length; index++) {
  59966. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  59967. }
  59968. ;
  59969. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  59970. this.pad.x = this.leftStick.x;
  59971. this.pad.y = this.leftStick.y;
  59972. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  59973. }
  59974. };
  59975. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  59976. if (!newState) {
  59977. newState = {
  59978. pressed: false,
  59979. touched: false,
  59980. value: 0
  59981. };
  59982. }
  59983. if (!currentState) {
  59984. this._buttons[buttonIndex] = {
  59985. pressed: newState.pressed,
  59986. touched: newState.touched,
  59987. value: newState.value
  59988. };
  59989. return;
  59990. }
  59991. this._checkChanges(newState, currentState);
  59992. if (this._changes.changed) {
  59993. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  59994. this.handleButtonChange(buttonIndex, newState, this._changes);
  59995. }
  59996. this._buttons[buttonIndex].pressed = newState.pressed;
  59997. this._buttons[buttonIndex].touched = newState.touched;
  59998. // oculus triggers are never 0, thou not touched.
  59999. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60000. };
  60001. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60002. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60003. this._changes.touchChanged = newState.touched !== currentState.touched;
  60004. this._changes.valueChanged = newState.value !== currentState.value;
  60005. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60006. return this._changes;
  60007. };
  60008. WebVRController.prototype.dispose = function () {
  60009. _super.prototype.dispose.call(this);
  60010. this.onTriggerStateChangedObservable.clear();
  60011. this.onMainButtonStateChangedObservable.clear();
  60012. this.onSecondaryButtonStateChangedObservable.clear();
  60013. this.onPadStateChangedObservable.clear();
  60014. this.onPadValuesChangedObservable.clear();
  60015. };
  60016. return WebVRController;
  60017. }(BABYLON.PoseEnabledController));
  60018. BABYLON.WebVRController = WebVRController;
  60019. })(BABYLON || (BABYLON = {}));
  60020. //# sourceMappingURL=babylon.webVRController.js.map
  60021. var BABYLON;
  60022. (function (BABYLON) {
  60023. var OculusTouchController = /** @class */ (function (_super) {
  60024. __extends(OculusTouchController, _super);
  60025. function OculusTouchController(vrGamepad) {
  60026. var _this = _super.call(this, vrGamepad) || this;
  60027. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60028. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60029. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60030. return _this;
  60031. }
  60032. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60033. var _this = this;
  60034. var meshName;
  60035. // Hand
  60036. if (this.hand === 'left') {
  60037. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60038. }
  60039. else {
  60040. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60041. }
  60042. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60043. /*
  60044. Parent Mesh name: oculus_touch_left
  60045. - body
  60046. - trigger
  60047. - thumbstick
  60048. - grip
  60049. - button_y
  60050. - button_x
  60051. - button_enter
  60052. */
  60053. _this._defaultModel = newMeshes[1];
  60054. _this.attachToMesh(_this._defaultModel);
  60055. if (meshLoaded) {
  60056. meshLoaded(_this._defaultModel);
  60057. }
  60058. });
  60059. };
  60060. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60061. // helper getters for left and right hand.
  60062. get: function () {
  60063. if (this.hand === 'right') {
  60064. return this.onMainButtonStateChangedObservable;
  60065. }
  60066. else {
  60067. throw new Error('No A button on left hand');
  60068. }
  60069. },
  60070. enumerable: true,
  60071. configurable: true
  60072. });
  60073. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60074. get: function () {
  60075. if (this.hand === 'right') {
  60076. return this.onSecondaryButtonStateChangedObservable;
  60077. }
  60078. else {
  60079. throw new Error('No B button on left hand');
  60080. }
  60081. },
  60082. enumerable: true,
  60083. configurable: true
  60084. });
  60085. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60086. get: function () {
  60087. if (this.hand === 'left') {
  60088. return this.onMainButtonStateChangedObservable;
  60089. }
  60090. else {
  60091. throw new Error('No X button on right hand');
  60092. }
  60093. },
  60094. enumerable: true,
  60095. configurable: true
  60096. });
  60097. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60098. get: function () {
  60099. if (this.hand === 'left') {
  60100. return this.onSecondaryButtonStateChangedObservable;
  60101. }
  60102. else {
  60103. throw new Error('No Y button on right hand');
  60104. }
  60105. },
  60106. enumerable: true,
  60107. configurable: true
  60108. });
  60109. /*
  60110. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60111. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60112. 2) secondary trigger (same)
  60113. 3) A (right) X (left), touch, pressed = value
  60114. 4) B / Y
  60115. 5) thumb rest
  60116. */
  60117. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60118. var notifyObject = state; //{ state: state, changes: changes };
  60119. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60120. switch (buttonIdx) {
  60121. case 0:
  60122. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60123. return;
  60124. case 1:// index trigger
  60125. if (this._defaultModel) {
  60126. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60127. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60128. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60129. }
  60130. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60131. return;
  60132. case 2:// secondary trigger
  60133. if (this._defaultModel) {
  60134. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60135. }
  60136. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60137. return;
  60138. case 3:
  60139. if (this._defaultModel) {
  60140. if (notifyObject.pressed) {
  60141. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60142. }
  60143. else {
  60144. (this._defaultModel.getChildren()[1]).position.y = 0;
  60145. }
  60146. }
  60147. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60148. return;
  60149. case 4:
  60150. if (this._defaultModel) {
  60151. if (notifyObject.pressed) {
  60152. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60153. }
  60154. else {
  60155. (this._defaultModel.getChildren()[2]).position.y = 0;
  60156. }
  60157. }
  60158. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60159. return;
  60160. case 5:
  60161. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60162. return;
  60163. }
  60164. };
  60165. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60166. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60167. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60168. return OculusTouchController;
  60169. }(BABYLON.WebVRController));
  60170. BABYLON.OculusTouchController = OculusTouchController;
  60171. })(BABYLON || (BABYLON = {}));
  60172. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60173. var BABYLON;
  60174. (function (BABYLON) {
  60175. var ViveController = /** @class */ (function (_super) {
  60176. __extends(ViveController, _super);
  60177. function ViveController(vrGamepad) {
  60178. var _this = _super.call(this, vrGamepad) || this;
  60179. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60180. _this._invertLeftStickY = true;
  60181. return _this;
  60182. }
  60183. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60184. var _this = this;
  60185. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60186. /*
  60187. Parent Mesh name: ViveWand
  60188. - body
  60189. - r_gripper
  60190. - l_gripper
  60191. - menu_button
  60192. - system_button
  60193. - trackpad
  60194. - trigger
  60195. - LED
  60196. */
  60197. _this._defaultModel = newMeshes[1];
  60198. _this.attachToMesh(_this._defaultModel);
  60199. if (meshLoaded) {
  60200. meshLoaded(_this._defaultModel);
  60201. }
  60202. });
  60203. };
  60204. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60205. get: function () {
  60206. return this.onMainButtonStateChangedObservable;
  60207. },
  60208. enumerable: true,
  60209. configurable: true
  60210. });
  60211. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60212. get: function () {
  60213. return this.onMainButtonStateChangedObservable;
  60214. },
  60215. enumerable: true,
  60216. configurable: true
  60217. });
  60218. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60219. get: function () {
  60220. return this.onSecondaryButtonStateChangedObservable;
  60221. },
  60222. enumerable: true,
  60223. configurable: true
  60224. });
  60225. /**
  60226. * Vive mapping:
  60227. * 0: touchpad
  60228. * 1: trigger
  60229. * 2: left AND right buttons
  60230. * 3: menu button
  60231. */
  60232. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60233. var notifyObject = state; //{ state: state, changes: changes };
  60234. switch (buttonIdx) {
  60235. case 0:
  60236. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60237. return;
  60238. case 1:// index trigger
  60239. if (this._defaultModel) {
  60240. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  60241. }
  60242. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60243. return;
  60244. case 2:// left AND right button
  60245. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60246. return;
  60247. case 3:
  60248. if (this._defaultModel) {
  60249. if (notifyObject.pressed) {
  60250. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60251. }
  60252. else {
  60253. (this._defaultModel.getChildren()[2]).position.y = 0;
  60254. }
  60255. }
  60256. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60257. return;
  60258. }
  60259. };
  60260. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  60261. ViveController.MODEL_FILENAME = 'wand.babylon';
  60262. return ViveController;
  60263. }(BABYLON.WebVRController));
  60264. BABYLON.ViveController = ViveController;
  60265. })(BABYLON || (BABYLON = {}));
  60266. //# sourceMappingURL=babylon.viveController.js.map
  60267. var BABYLON;
  60268. (function (BABYLON) {
  60269. var GenericController = /** @class */ (function (_super) {
  60270. __extends(GenericController, _super);
  60271. function GenericController(vrGamepad) {
  60272. return _super.call(this, vrGamepad) || this;
  60273. }
  60274. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60275. var _this = this;
  60276. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  60277. _this._defaultModel = newMeshes[1];
  60278. _this.attachToMesh(_this._defaultModel);
  60279. if (meshLoaded) {
  60280. meshLoaded(_this._defaultModel);
  60281. }
  60282. });
  60283. };
  60284. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60285. console.log("Button id: " + buttonIdx + "state: ");
  60286. console.dir(state);
  60287. };
  60288. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60289. GenericController.MODEL_FILENAME = 'generic.babylon';
  60290. return GenericController;
  60291. }(BABYLON.WebVRController));
  60292. BABYLON.GenericController = GenericController;
  60293. })(BABYLON || (BABYLON = {}));
  60294. //# sourceMappingURL=babylon.genericController.js.map
  60295. var BABYLON;
  60296. (function (BABYLON) {
  60297. var LoadedMeshInfo = /** @class */ (function () {
  60298. function LoadedMeshInfo() {
  60299. this.buttonMeshes = {};
  60300. this.axisMeshes = {};
  60301. }
  60302. return LoadedMeshInfo;
  60303. }());
  60304. var WindowsMotionController = /** @class */ (function (_super) {
  60305. __extends(WindowsMotionController, _super);
  60306. function WindowsMotionController(vrGamepad) {
  60307. var _this = _super.call(this, vrGamepad) || this;
  60308. _this._mapping = {
  60309. // Semantic button names
  60310. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  60311. // A mapping of the button name to glTF model node name
  60312. // that should be transformed by button value.
  60313. buttonMeshNames: {
  60314. 'trigger': 'SELECT',
  60315. 'menu': 'MENU',
  60316. 'grip': 'GRASP',
  60317. 'thumbstick': 'THUMBSTICK_PRESS',
  60318. 'trackpad': 'TOUCHPAD_PRESS'
  60319. },
  60320. // This mapping is used to translate from the Motion Controller to Babylon semantics
  60321. buttonObservableNames: {
  60322. 'trigger': 'onTriggerStateChangedObservable',
  60323. 'menu': 'onSecondaryButtonStateChangedObservable',
  60324. 'grip': 'onMainButtonStateChangedObservable',
  60325. 'thumbstick': 'onPadStateChangedObservable',
  60326. 'trackpad': 'onTrackpadChangedObservable'
  60327. },
  60328. // A mapping of the axis name to glTF model node name
  60329. // that should be transformed by axis value.
  60330. // This array mirrors the browserGamepad.axes array, such that
  60331. // the mesh corresponding to axis 0 is in this array index 0.
  60332. axisMeshNames: [
  60333. 'THUMBSTICK_X',
  60334. 'THUMBSTICK_Y',
  60335. 'TOUCHPAD_TOUCH_X',
  60336. 'TOUCHPAD_TOUCH_Y'
  60337. ],
  60338. pointingPoseMeshName: 'POINTING_POSE'
  60339. };
  60340. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  60341. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  60342. _this.trackpad = { x: 0, y: 0 };
  60343. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  60344. _this._loadedMeshInfo = null;
  60345. return _this;
  60346. }
  60347. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  60348. get: function () {
  60349. return this.onTriggerStateChangedObservable;
  60350. },
  60351. enumerable: true,
  60352. configurable: true
  60353. });
  60354. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  60355. get: function () {
  60356. return this.onSecondaryButtonStateChangedObservable;
  60357. },
  60358. enumerable: true,
  60359. configurable: true
  60360. });
  60361. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  60362. get: function () {
  60363. return this.onMainButtonStateChangedObservable;
  60364. },
  60365. enumerable: true,
  60366. configurable: true
  60367. });
  60368. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  60369. get: function () {
  60370. return this.onPadStateChangedObservable;
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  60376. get: function () {
  60377. return this.onTrackpadChangedObservable;
  60378. },
  60379. enumerable: true,
  60380. configurable: true
  60381. });
  60382. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  60383. get: function () {
  60384. return this.onTrackpadValuesChangedObservable;
  60385. },
  60386. enumerable: true,
  60387. configurable: true
  60388. });
  60389. /**
  60390. * Called once per frame by the engine.
  60391. */
  60392. WindowsMotionController.prototype.update = function () {
  60393. _super.prototype.update.call(this);
  60394. // Only need to animate axes if there is a loaded mesh
  60395. if (this._loadedMeshInfo) {
  60396. if (this.browserGamepad.axes) {
  60397. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  60398. this.trackpad.x = this.browserGamepad["axes"][2];
  60399. this.trackpad.y = this.browserGamepad["axes"][3];
  60400. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  60401. }
  60402. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  60403. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  60404. }
  60405. }
  60406. }
  60407. };
  60408. /**
  60409. * Called once for each button that changed state since the last frame
  60410. * @param buttonIdx Which button index changed
  60411. * @param state New state of the button
  60412. * @param changes Which properties on the state changed since last frame
  60413. */
  60414. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60415. var buttonName = this._mapping.buttons[buttonIdx];
  60416. if (!buttonName) {
  60417. return;
  60418. }
  60419. // Only emit events for buttons that we know how to map from index to name
  60420. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  60421. if (observable) {
  60422. observable.notifyObservers(state);
  60423. }
  60424. this.lerpButtonTransform(buttonName, state.value);
  60425. };
  60426. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  60427. // If there is no loaded mesh, there is nothing to transform.
  60428. if (!this._loadedMeshInfo) {
  60429. return;
  60430. }
  60431. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  60432. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60433. return;
  60434. }
  60435. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  60436. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  60437. };
  60438. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  60439. if (!this._loadedMeshInfo) {
  60440. return;
  60441. }
  60442. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  60443. if (!meshInfo) {
  60444. return;
  60445. }
  60446. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60447. return;
  60448. }
  60449. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  60450. var lerpValue = axisValue * 0.5 + 0.5;
  60451. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  60452. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  60453. };
  60454. /**
  60455. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  60456. * @param scene scene in which to add meshes
  60457. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  60458. */
  60459. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  60460. var _this = this;
  60461. if (forceDefault === void 0) { forceDefault = false; }
  60462. var path;
  60463. var filename;
  60464. // Checking if GLB loader is present
  60465. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  60466. // Determine the device specific folder based on the ID suffix
  60467. var device = 'default';
  60468. if (this.id && !forceDefault) {
  60469. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  60470. device = ((match && match[0]) || device);
  60471. }
  60472. // Hand
  60473. if (this.hand === 'left') {
  60474. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  60475. }
  60476. else {
  60477. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  60478. }
  60479. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  60480. }
  60481. else {
  60482. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  60483. path = BABYLON.GenericController.MODEL_BASE_URL;
  60484. filename = BABYLON.GenericController.MODEL_FILENAME;
  60485. }
  60486. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  60487. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  60488. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  60489. if (!_this._loadedMeshInfo) {
  60490. return;
  60491. }
  60492. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  60493. _this.attachToMesh(_this._defaultModel);
  60494. if (meshLoaded) {
  60495. meshLoaded(_this._defaultModel);
  60496. }
  60497. }, null, function (scene, message) {
  60498. BABYLON.Tools.Log(message);
  60499. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  60500. if (!forceDefault) {
  60501. _this.initControllerMesh(scene, meshLoaded, true);
  60502. }
  60503. });
  60504. };
  60505. /**
  60506. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  60507. * can be transformed by button presses and axes values, based on this._mapping.
  60508. *
  60509. * @param scene scene in which the meshes exist
  60510. * @param meshes list of meshes that make up the controller model to process
  60511. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  60512. */
  60513. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  60514. var loadedMeshInfo = null;
  60515. // Create a new mesh to contain the glTF hierarchy
  60516. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  60517. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  60518. var childMesh = null;
  60519. for (var i = 0; i < meshes.length; i++) {
  60520. var mesh = meshes[i];
  60521. if (!mesh.parent) {
  60522. // Exclude controller meshes from picking results
  60523. mesh.isPickable = false;
  60524. // Handle root node, attach to the new parentMesh
  60525. childMesh = mesh;
  60526. break;
  60527. }
  60528. }
  60529. if (childMesh) {
  60530. childMesh.setParent(parentMesh);
  60531. // Create our mesh info. Note that this method will always return non-null.
  60532. loadedMeshInfo = this.createMeshInfo(parentMesh);
  60533. }
  60534. else {
  60535. BABYLON.Tools.Warn('Could not find root node in model file.');
  60536. }
  60537. return loadedMeshInfo;
  60538. };
  60539. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  60540. var loadedMeshInfo = new LoadedMeshInfo();
  60541. var i;
  60542. loadedMeshInfo.rootNode = rootNode;
  60543. // Reset the caches
  60544. loadedMeshInfo.buttonMeshes = {};
  60545. loadedMeshInfo.axisMeshes = {};
  60546. // Button Meshes
  60547. for (i = 0; i < this._mapping.buttons.length; i++) {
  60548. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  60549. if (!buttonMeshName) {
  60550. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  60551. continue;
  60552. }
  60553. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  60554. if (!buttonMesh) {
  60555. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  60556. continue;
  60557. }
  60558. var buttonMeshInfo = {
  60559. index: i,
  60560. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  60561. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  60562. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  60563. };
  60564. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  60565. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  60566. }
  60567. else {
  60568. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  60569. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  60570. '(VALUE: ' + !!buttonMeshInfo.value +
  60571. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  60572. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  60573. ')');
  60574. }
  60575. }
  60576. // Axis Meshes
  60577. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  60578. var axisMeshName = this._mapping.axisMeshNames[i];
  60579. if (!axisMeshName) {
  60580. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  60581. continue;
  60582. }
  60583. var axisMesh = getChildByName(rootNode, axisMeshName);
  60584. if (!axisMesh) {
  60585. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  60586. continue;
  60587. }
  60588. var axisMeshInfo = {
  60589. index: i,
  60590. value: getImmediateChildByName(axisMesh, 'VALUE'),
  60591. min: getImmediateChildByName(axisMesh, 'MIN'),
  60592. max: getImmediateChildByName(axisMesh, 'MAX')
  60593. };
  60594. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  60595. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  60596. }
  60597. else {
  60598. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  60599. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  60600. '(VALUE: ' + !!axisMeshInfo.value +
  60601. ', MIN: ' + !!axisMeshInfo.min +
  60602. ', MAX:' + !!axisMeshInfo.max +
  60603. ')');
  60604. }
  60605. }
  60606. // Pointing Ray
  60607. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  60608. if (!loadedMeshInfo.pointingPoseNode) {
  60609. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  60610. }
  60611. return loadedMeshInfo;
  60612. // Look through all children recursively. This will return null if no mesh exists with the given name.
  60613. function getChildByName(node, name) {
  60614. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  60615. }
  60616. // Look through only immediate children. This will return null if no mesh exists with the given name.
  60617. function getImmediateChildByName(node, name) {
  60618. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  60619. }
  60620. };
  60621. WindowsMotionController.prototype.getForwardRay = function (length) {
  60622. if (length === void 0) { length = 100; }
  60623. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  60624. return _super.prototype.getForwardRay.call(this, length);
  60625. }
  60626. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  60627. var origin = m.getTranslation();
  60628. var forward = new BABYLON.Vector3(0, 0, -1);
  60629. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60630. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60631. return new BABYLON.Ray(origin, direction, length);
  60632. };
  60633. WindowsMotionController.prototype.dispose = function () {
  60634. _super.prototype.dispose.call(this);
  60635. this.onTrackpadChangedObservable.clear();
  60636. };
  60637. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  60638. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  60639. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  60640. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  60641. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  60642. return WindowsMotionController;
  60643. }(BABYLON.WebVRController));
  60644. BABYLON.WindowsMotionController = WindowsMotionController;
  60645. })(BABYLON || (BABYLON = {}));
  60646. //# sourceMappingURL=babylon.windowsMotionController.js.map
  60647. var BABYLON;
  60648. (function (BABYLON) {
  60649. var GearVRController = /** @class */ (function (_super) {
  60650. __extends(GearVRController, _super);
  60651. function GearVRController(vrGamepad) {
  60652. var _this = _super.call(this, vrGamepad) || this;
  60653. _this._buttonIndexToObservableNameMap = [
  60654. 'onTrackpadChangedObservable',
  60655. 'onTriggerStateChangedObservable' // Trigger
  60656. ];
  60657. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  60658. return _this;
  60659. }
  60660. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60661. var _this = this;
  60662. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  60663. _this._defaultModel = newMeshes[1];
  60664. _this.attachToMesh(_this._defaultModel);
  60665. if (meshLoaded) {
  60666. meshLoaded(_this._defaultModel);
  60667. }
  60668. });
  60669. };
  60670. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60671. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  60672. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  60673. // Only emit events for buttons that we know how to map from index to observable
  60674. var observable = this[observableName];
  60675. if (observable) {
  60676. observable.notifyObservers(state);
  60677. }
  60678. }
  60679. };
  60680. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60681. GearVRController.MODEL_FILENAME = 'generic.babylon';
  60682. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  60683. return GearVRController;
  60684. }(BABYLON.WebVRController));
  60685. BABYLON.GearVRController = GearVRController;
  60686. })(BABYLON || (BABYLON = {}));
  60687. //# sourceMappingURL=babylon.gearVRController.js.map
  60688. var BABYLON;
  60689. (function (BABYLON) {
  60690. var FollowCamera = /** @class */ (function (_super) {
  60691. __extends(FollowCamera, _super);
  60692. function FollowCamera(name, position, scene, lockedTarget) {
  60693. if (lockedTarget === void 0) { lockedTarget = null; }
  60694. var _this = _super.call(this, name, position, scene) || this;
  60695. _this.radius = 12;
  60696. _this.rotationOffset = 0;
  60697. _this.heightOffset = 4;
  60698. _this.cameraAcceleration = 0.05;
  60699. _this.maxCameraSpeed = 20;
  60700. _this.lockedTarget = lockedTarget;
  60701. return _this;
  60702. }
  60703. FollowCamera.prototype.getRadians = function (degrees) {
  60704. return degrees * Math.PI / 180;
  60705. };
  60706. FollowCamera.prototype.follow = function (cameraTarget) {
  60707. if (!cameraTarget)
  60708. return;
  60709. var yRotation;
  60710. if (cameraTarget.rotationQuaternion) {
  60711. var rotMatrix = new BABYLON.Matrix();
  60712. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  60713. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  60714. }
  60715. else {
  60716. yRotation = cameraTarget.rotation.y;
  60717. }
  60718. var radians = this.getRadians(this.rotationOffset) + yRotation;
  60719. var targetPosition = cameraTarget.getAbsolutePosition();
  60720. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  60721. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  60722. var dx = targetX - this.position.x;
  60723. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  60724. var dz = (targetZ) - this.position.z;
  60725. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  60726. var vy = dy * this.cameraAcceleration;
  60727. var vz = dz * this.cameraAcceleration * 2;
  60728. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  60729. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60730. }
  60731. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  60732. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60733. }
  60734. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  60735. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  60736. }
  60737. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  60738. this.setTarget(targetPosition);
  60739. };
  60740. FollowCamera.prototype._checkInputs = function () {
  60741. _super.prototype._checkInputs.call(this);
  60742. if (this.lockedTarget) {
  60743. this.follow(this.lockedTarget);
  60744. }
  60745. };
  60746. FollowCamera.prototype.getClassName = function () {
  60747. return "FollowCamera";
  60748. };
  60749. __decorate([
  60750. BABYLON.serialize()
  60751. ], FollowCamera.prototype, "radius", void 0);
  60752. __decorate([
  60753. BABYLON.serialize()
  60754. ], FollowCamera.prototype, "rotationOffset", void 0);
  60755. __decorate([
  60756. BABYLON.serialize()
  60757. ], FollowCamera.prototype, "heightOffset", void 0);
  60758. __decorate([
  60759. BABYLON.serialize()
  60760. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  60761. __decorate([
  60762. BABYLON.serialize()
  60763. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  60764. __decorate([
  60765. BABYLON.serializeAsMeshReference("lockedTargetId")
  60766. ], FollowCamera.prototype, "lockedTarget", void 0);
  60767. return FollowCamera;
  60768. }(BABYLON.TargetCamera));
  60769. BABYLON.FollowCamera = FollowCamera;
  60770. var ArcFollowCamera = /** @class */ (function (_super) {
  60771. __extends(ArcFollowCamera, _super);
  60772. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  60773. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  60774. _this.alpha = alpha;
  60775. _this.beta = beta;
  60776. _this.radius = radius;
  60777. _this.target = target;
  60778. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  60779. _this.follow();
  60780. return _this;
  60781. }
  60782. ArcFollowCamera.prototype.follow = function () {
  60783. if (!this.target) {
  60784. return;
  60785. }
  60786. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  60787. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  60788. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  60789. var targetPosition = this.target.getAbsolutePosition();
  60790. this.position = targetPosition.add(this._cartesianCoordinates);
  60791. this.setTarget(targetPosition);
  60792. };
  60793. ArcFollowCamera.prototype._checkInputs = function () {
  60794. _super.prototype._checkInputs.call(this);
  60795. this.follow();
  60796. };
  60797. ArcFollowCamera.prototype.getClassName = function () {
  60798. return "ArcFollowCamera";
  60799. };
  60800. return ArcFollowCamera;
  60801. }(BABYLON.TargetCamera));
  60802. BABYLON.ArcFollowCamera = ArcFollowCamera;
  60803. })(BABYLON || (BABYLON = {}));
  60804. //# sourceMappingURL=babylon.followCamera.js.map
  60805. var BABYLON;
  60806. (function (BABYLON) {
  60807. // We're mainly based on the logic defined into the FreeCamera code
  60808. var UniversalCamera = /** @class */ (function (_super) {
  60809. __extends(UniversalCamera, _super);
  60810. //-- end properties for backward compatibility for inputs
  60811. function UniversalCamera(name, position, scene) {
  60812. var _this = _super.call(this, name, position, scene) || this;
  60813. _this.inputs.addGamepad();
  60814. return _this;
  60815. }
  60816. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  60817. //-- Begin properties for backward compatibility for inputs
  60818. get: function () {
  60819. var gamepad = this.inputs.attached["gamepad"];
  60820. if (gamepad)
  60821. return gamepad.gamepadAngularSensibility;
  60822. return 0;
  60823. },
  60824. set: function (value) {
  60825. var gamepad = this.inputs.attached["gamepad"];
  60826. if (gamepad)
  60827. gamepad.gamepadAngularSensibility = value;
  60828. },
  60829. enumerable: true,
  60830. configurable: true
  60831. });
  60832. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  60833. get: function () {
  60834. var gamepad = this.inputs.attached["gamepad"];
  60835. if (gamepad)
  60836. return gamepad.gamepadMoveSensibility;
  60837. return 0;
  60838. },
  60839. set: function (value) {
  60840. var gamepad = this.inputs.attached["gamepad"];
  60841. if (gamepad)
  60842. gamepad.gamepadMoveSensibility = value;
  60843. },
  60844. enumerable: true,
  60845. configurable: true
  60846. });
  60847. UniversalCamera.prototype.getClassName = function () {
  60848. return "UniversalCamera";
  60849. };
  60850. return UniversalCamera;
  60851. }(BABYLON.TouchCamera));
  60852. BABYLON.UniversalCamera = UniversalCamera;
  60853. })(BABYLON || (BABYLON = {}));
  60854. //# sourceMappingURL=babylon.universalCamera.js.map
  60855. var BABYLON;
  60856. (function (BABYLON) {
  60857. // We're mainly based on the logic defined into the FreeCamera code
  60858. var GamepadCamera = /** @class */ (function (_super) {
  60859. __extends(GamepadCamera, _super);
  60860. //-- end properties for backward compatibility for inputs
  60861. function GamepadCamera(name, position, scene) {
  60862. return _super.call(this, name, position, scene) || this;
  60863. }
  60864. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  60865. //-- Begin properties for backward compatibility for inputs
  60866. get: function () {
  60867. var gamepad = this.inputs.attached["gamepad"];
  60868. if (gamepad)
  60869. return gamepad.gamepadAngularSensibility;
  60870. return 0;
  60871. },
  60872. set: function (value) {
  60873. var gamepad = this.inputs.attached["gamepad"];
  60874. if (gamepad)
  60875. gamepad.gamepadAngularSensibility = value;
  60876. },
  60877. enumerable: true,
  60878. configurable: true
  60879. });
  60880. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  60881. get: function () {
  60882. var gamepad = this.inputs.attached["gamepad"];
  60883. if (gamepad)
  60884. return gamepad.gamepadMoveSensibility;
  60885. return 0;
  60886. },
  60887. set: function (value) {
  60888. var gamepad = this.inputs.attached["gamepad"];
  60889. if (gamepad)
  60890. gamepad.gamepadMoveSensibility = value;
  60891. },
  60892. enumerable: true,
  60893. configurable: true
  60894. });
  60895. GamepadCamera.prototype.getClassName = function () {
  60896. return "GamepadCamera";
  60897. };
  60898. return GamepadCamera;
  60899. }(BABYLON.UniversalCamera));
  60900. BABYLON.GamepadCamera = GamepadCamera;
  60901. })(BABYLON || (BABYLON = {}));
  60902. //# sourceMappingURL=babylon.gamepadCamera.js.map
  60903. var BABYLON;
  60904. (function (BABYLON) {
  60905. var PostProcessRenderPipelineManager = /** @class */ (function () {
  60906. function PostProcessRenderPipelineManager() {
  60907. this._renderPipelines = {};
  60908. }
  60909. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  60910. this._renderPipelines[renderPipeline._name] = renderPipeline;
  60911. };
  60912. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  60913. if (unique === void 0) { unique = false; }
  60914. var renderPipeline = this._renderPipelines[renderPipelineName];
  60915. if (!renderPipeline) {
  60916. return;
  60917. }
  60918. renderPipeline._attachCameras(cameras, unique);
  60919. };
  60920. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  60921. var renderPipeline = this._renderPipelines[renderPipelineName];
  60922. if (!renderPipeline) {
  60923. return;
  60924. }
  60925. renderPipeline._detachCameras(cameras);
  60926. };
  60927. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  60928. var renderPipeline = this._renderPipelines[renderPipelineName];
  60929. if (!renderPipeline) {
  60930. return;
  60931. }
  60932. renderPipeline._enableEffect(renderEffectName, cameras);
  60933. };
  60934. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  60935. var renderPipeline = this._renderPipelines[renderPipelineName];
  60936. if (!renderPipeline) {
  60937. return;
  60938. }
  60939. renderPipeline._disableEffect(renderEffectName, cameras);
  60940. };
  60941. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  60942. var renderPipeline = this._renderPipelines[renderPipelineName];
  60943. if (!renderPipeline) {
  60944. return;
  60945. }
  60946. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  60947. };
  60948. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  60949. var renderPipeline = this._renderPipelines[renderPipelineName];
  60950. if (!renderPipeline) {
  60951. return;
  60952. }
  60953. renderPipeline._disableDisplayOnlyPass(cameras);
  60954. };
  60955. PostProcessRenderPipelineManager.prototype.update = function () {
  60956. for (var renderPipelineName in this._renderPipelines) {
  60957. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  60958. var pipeline = this._renderPipelines[renderPipelineName];
  60959. if (!pipeline.isSupported) {
  60960. pipeline.dispose();
  60961. delete this._renderPipelines[renderPipelineName];
  60962. }
  60963. else {
  60964. pipeline._update();
  60965. }
  60966. }
  60967. }
  60968. };
  60969. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  60970. for (var renderPipelineName in this._renderPipelines) {
  60971. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  60972. var pipeline = this._renderPipelines[renderPipelineName];
  60973. pipeline._rebuild();
  60974. }
  60975. }
  60976. };
  60977. PostProcessRenderPipelineManager.prototype.dispose = function () {
  60978. for (var renderPipelineName in this._renderPipelines) {
  60979. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  60980. var pipeline = this._renderPipelines[renderPipelineName];
  60981. pipeline.dispose();
  60982. }
  60983. }
  60984. };
  60985. return PostProcessRenderPipelineManager;
  60986. }());
  60987. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  60988. })(BABYLON || (BABYLON = {}));
  60989. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  60990. var BABYLON;
  60991. (function (BABYLON) {
  60992. var PostProcessRenderPass = /** @class */ (function () {
  60993. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  60994. this._refCount = 0;
  60995. this._name = name;
  60996. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  60997. this.setRenderList(renderList);
  60998. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  60999. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61000. this._scene = scene;
  61001. this._renderList = renderList;
  61002. }
  61003. // private
  61004. PostProcessRenderPass.prototype._incRefCount = function () {
  61005. if (this._refCount === 0) {
  61006. this._scene.customRenderTargets.push(this._renderTexture);
  61007. }
  61008. return ++this._refCount;
  61009. };
  61010. PostProcessRenderPass.prototype._decRefCount = function () {
  61011. this._refCount--;
  61012. if (this._refCount <= 0) {
  61013. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61014. }
  61015. return this._refCount;
  61016. };
  61017. PostProcessRenderPass.prototype._update = function () {
  61018. this.setRenderList(this._renderList);
  61019. };
  61020. // public
  61021. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61022. this._renderTexture.renderList = renderList;
  61023. };
  61024. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61025. return this._renderTexture;
  61026. };
  61027. return PostProcessRenderPass;
  61028. }());
  61029. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61030. })(BABYLON || (BABYLON = {}));
  61031. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61032. var BABYLON;
  61033. (function (BABYLON) {
  61034. var PostProcessRenderEffect = /** @class */ (function () {
  61035. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61036. this._name = name;
  61037. this._singleInstance = singleInstance || true;
  61038. this._getPostProcess = getPostProcess;
  61039. this._cameras = {};
  61040. this._indicesForCamera = {};
  61041. this._postProcesses = {};
  61042. this._renderPasses = {};
  61043. this._renderEffectAsPasses = {};
  61044. }
  61045. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61046. get: function () {
  61047. for (var index in this._postProcesses) {
  61048. if (!this._postProcesses[index].isSupported) {
  61049. return false;
  61050. }
  61051. }
  61052. return true;
  61053. },
  61054. enumerable: true,
  61055. configurable: true
  61056. });
  61057. PostProcessRenderEffect.prototype._update = function () {
  61058. for (var renderPassName in this._renderPasses) {
  61059. this._renderPasses[renderPassName]._update();
  61060. }
  61061. };
  61062. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61063. this._renderPasses[renderPass._name] = renderPass;
  61064. this._linkParameters();
  61065. };
  61066. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61067. delete this._renderPasses[renderPass._name];
  61068. this._linkParameters();
  61069. };
  61070. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61071. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61072. this._linkParameters();
  61073. };
  61074. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61075. for (var renderPassName in this._renderPasses) {
  61076. if (renderPassName === passName) {
  61077. return this._renderPasses[passName];
  61078. }
  61079. }
  61080. return null;
  61081. };
  61082. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61083. this._renderPasses = {};
  61084. this._linkParameters();
  61085. };
  61086. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61087. var cameraKey;
  61088. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61089. if (!cams) {
  61090. return;
  61091. }
  61092. for (var i = 0; i < cams.length; i++) {
  61093. var camera = cams[i];
  61094. var cameraName = camera.name;
  61095. if (this._singleInstance) {
  61096. cameraKey = 0;
  61097. }
  61098. else {
  61099. cameraKey = cameraName;
  61100. }
  61101. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61102. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61103. if (!this._indicesForCamera[cameraName]) {
  61104. this._indicesForCamera[cameraName] = [];
  61105. }
  61106. this._indicesForCamera[cameraName].push(index);
  61107. if (!this._cameras[cameraName]) {
  61108. this._cameras[cameraName] = camera;
  61109. }
  61110. for (var passName in this._renderPasses) {
  61111. this._renderPasses[passName]._incRefCount();
  61112. }
  61113. }
  61114. this._linkParameters();
  61115. };
  61116. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61117. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61118. if (!cams) {
  61119. return;
  61120. }
  61121. for (var i = 0; i < cams.length; i++) {
  61122. var camera = cams[i];
  61123. var cameraName = camera.name;
  61124. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61125. if (this._cameras[cameraName]) {
  61126. //this._indicesForCamera.splice(index, 1);
  61127. this._cameras[cameraName] = null;
  61128. }
  61129. for (var passName in this._renderPasses) {
  61130. this._renderPasses[passName]._decRefCount();
  61131. }
  61132. }
  61133. };
  61134. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61135. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61136. if (!cams) {
  61137. return;
  61138. }
  61139. for (var i = 0; i < cams.length; i++) {
  61140. var camera = cams[i];
  61141. var cameraName = camera.name;
  61142. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61143. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61144. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61145. }
  61146. }
  61147. for (var passName in this._renderPasses) {
  61148. this._renderPasses[passName]._incRefCount();
  61149. }
  61150. }
  61151. };
  61152. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61153. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61154. if (!cams) {
  61155. return;
  61156. }
  61157. for (var i = 0; i < cams.length; i++) {
  61158. var camera = cams[i];
  61159. var cameraName = camera.Name;
  61160. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61161. for (var passName in this._renderPasses) {
  61162. this._renderPasses[passName]._decRefCount();
  61163. }
  61164. }
  61165. };
  61166. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61167. if (this._singleInstance) {
  61168. return this._postProcesses[0];
  61169. }
  61170. else {
  61171. if (!camera) {
  61172. return null;
  61173. }
  61174. return this._postProcesses[camera.name];
  61175. }
  61176. };
  61177. PostProcessRenderEffect.prototype._linkParameters = function () {
  61178. var _this = this;
  61179. for (var index in this._postProcesses) {
  61180. if (this.applyParameters) {
  61181. this.applyParameters(this._postProcesses[index]);
  61182. }
  61183. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61184. _this._linkTextures(effect);
  61185. });
  61186. }
  61187. };
  61188. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61189. for (var renderPassName in this._renderPasses) {
  61190. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61191. }
  61192. for (var renderEffectName in this._renderEffectAsPasses) {
  61193. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61194. }
  61195. };
  61196. return PostProcessRenderEffect;
  61197. }());
  61198. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61199. })(BABYLON || (BABYLON = {}));
  61200. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61201. var BABYLON;
  61202. (function (BABYLON) {
  61203. var PostProcessRenderPipeline = /** @class */ (function () {
  61204. function PostProcessRenderPipeline(engine, name) {
  61205. this._engine = engine;
  61206. this._name = name;
  61207. this._renderEffects = {};
  61208. this._renderEffectsForIsolatedPass = new Array();
  61209. this._cameras = [];
  61210. }
  61211. PostProcessRenderPipeline.prototype.getClassName = function () {
  61212. return "PostProcessRenderPipeline";
  61213. };
  61214. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61215. get: function () {
  61216. for (var renderEffectName in this._renderEffects) {
  61217. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61218. if (!this._renderEffects[renderEffectName].isSupported) {
  61219. return false;
  61220. }
  61221. }
  61222. }
  61223. return true;
  61224. },
  61225. enumerable: true,
  61226. configurable: true
  61227. });
  61228. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61229. this._renderEffects[renderEffect._name] = renderEffect;
  61230. };
  61231. // private
  61232. PostProcessRenderPipeline.prototype._rebuild = function () {
  61233. };
  61234. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  61235. var renderEffects = this._renderEffects[renderEffectName];
  61236. if (!renderEffects) {
  61237. return;
  61238. }
  61239. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61240. };
  61241. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  61242. var renderEffects = this._renderEffects[renderEffectName];
  61243. if (!renderEffects) {
  61244. return;
  61245. }
  61246. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61247. };
  61248. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  61249. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61250. if (!cams) {
  61251. return;
  61252. }
  61253. var indicesToDelete = [];
  61254. var i;
  61255. for (i = 0; i < cams.length; i++) {
  61256. var camera = cams[i];
  61257. var cameraName = camera.name;
  61258. if (this._cameras.indexOf(camera) === -1) {
  61259. this._cameras[cameraName] = camera;
  61260. }
  61261. else if (unique) {
  61262. indicesToDelete.push(i);
  61263. }
  61264. }
  61265. for (i = 0; i < indicesToDelete.length; i++) {
  61266. cameras.splice(indicesToDelete[i], 1);
  61267. }
  61268. for (var renderEffectName in this._renderEffects) {
  61269. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61270. this._renderEffects[renderEffectName]._attachCameras(cams);
  61271. }
  61272. }
  61273. };
  61274. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  61275. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61276. if (!cams) {
  61277. return;
  61278. }
  61279. for (var renderEffectName in this._renderEffects) {
  61280. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61281. this._renderEffects[renderEffectName]._detachCameras(cams);
  61282. }
  61283. }
  61284. for (var i = 0; i < cams.length; i++) {
  61285. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  61286. }
  61287. };
  61288. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  61289. var _this = this;
  61290. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61291. if (!cams) {
  61292. return;
  61293. }
  61294. var pass = null;
  61295. var renderEffectName;
  61296. for (renderEffectName in this._renderEffects) {
  61297. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61298. pass = this._renderEffects[renderEffectName].getPass(passName);
  61299. if (pass != null) {
  61300. break;
  61301. }
  61302. }
  61303. }
  61304. if (pass === null) {
  61305. return;
  61306. }
  61307. for (renderEffectName in this._renderEffects) {
  61308. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61309. this._renderEffects[renderEffectName]._disable(cams);
  61310. }
  61311. }
  61312. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  61313. for (var i = 0; i < cams.length; i++) {
  61314. var camera = cams[i];
  61315. var cameraName = camera.name;
  61316. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  61317. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  61318. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  61319. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  61320. }
  61321. };
  61322. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  61323. var _this = this;
  61324. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61325. if (!cams) {
  61326. return;
  61327. }
  61328. for (var i = 0; i < cams.length; i++) {
  61329. var camera = cams[i];
  61330. var cameraName = camera.name;
  61331. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  61332. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  61333. }
  61334. for (var renderEffectName in this._renderEffects) {
  61335. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61336. this._renderEffects[renderEffectName]._enable(cams);
  61337. }
  61338. }
  61339. };
  61340. PostProcessRenderPipeline.prototype._update = function () {
  61341. for (var renderEffectName in this._renderEffects) {
  61342. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61343. this._renderEffects[renderEffectName]._update();
  61344. }
  61345. }
  61346. for (var i = 0; i < this._cameras.length; i++) {
  61347. var cameraName = this._cameras[i].name;
  61348. if (this._renderEffectsForIsolatedPass[cameraName]) {
  61349. this._renderEffectsForIsolatedPass[cameraName]._update();
  61350. }
  61351. }
  61352. };
  61353. PostProcessRenderPipeline.prototype._reset = function () {
  61354. this._renderEffects = {};
  61355. this._renderEffectsForIsolatedPass = new Array();
  61356. };
  61357. PostProcessRenderPipeline.prototype.dispose = function () {
  61358. // Must be implemented by children
  61359. };
  61360. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  61361. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  61362. __decorate([
  61363. BABYLON.serialize()
  61364. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  61365. return PostProcessRenderPipeline;
  61366. }());
  61367. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  61368. })(BABYLON || (BABYLON = {}));
  61369. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  61370. var BABYLON;
  61371. (function (BABYLON) {
  61372. var DepthRenderer = /** @class */ (function () {
  61373. function DepthRenderer(scene, type) {
  61374. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  61375. var _this = this;
  61376. this._scene = scene;
  61377. var engine = scene.getEngine();
  61378. // Render target
  61379. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  61380. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61381. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61382. this._depthMap.refreshRate = 1;
  61383. this._depthMap.renderParticles = false;
  61384. this._depthMap.renderList = null;
  61385. // set default depth value to 1.0 (far away)
  61386. this._depthMap.onClearObservable.add(function (engine) {
  61387. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  61388. });
  61389. // Custom render function
  61390. var renderSubMesh = function (subMesh) {
  61391. var mesh = subMesh.getRenderingMesh();
  61392. var scene = _this._scene;
  61393. var engine = scene.getEngine();
  61394. var material = subMesh.getMaterial();
  61395. if (!material) {
  61396. return;
  61397. }
  61398. // Culling and reverse (right handed system)
  61399. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61400. // Managing instances
  61401. var batch = mesh._getInstancesRenderList(subMesh._id);
  61402. if (batch.mustReturn) {
  61403. return;
  61404. }
  61405. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61406. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  61407. engine.enableEffect(_this._effect);
  61408. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61409. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61410. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  61411. // Alpha test
  61412. if (material && material.needAlphaTesting()) {
  61413. var alphaTexture = material.getAlphaTestTexture();
  61414. if (alphaTexture) {
  61415. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61416. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61417. }
  61418. }
  61419. // Bones
  61420. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61421. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61422. }
  61423. // Draw
  61424. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61425. }
  61426. };
  61427. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61428. var index;
  61429. if (depthOnlySubMeshes.length) {
  61430. engine.setColorWrite(false);
  61431. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61432. renderSubMesh(depthOnlySubMeshes.data[index]);
  61433. }
  61434. engine.setColorWrite(true);
  61435. }
  61436. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61437. renderSubMesh(opaqueSubMeshes.data[index]);
  61438. }
  61439. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61440. renderSubMesh(alphaTestSubMeshes.data[index]);
  61441. }
  61442. };
  61443. }
  61444. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  61445. var material = subMesh.getMaterial();
  61446. if (material.disableDepthWrite) {
  61447. return false;
  61448. }
  61449. var defines = [];
  61450. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61451. var mesh = subMesh.getMesh();
  61452. // Alpha test
  61453. if (material && material.needAlphaTesting()) {
  61454. defines.push("#define ALPHATEST");
  61455. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61456. attribs.push(BABYLON.VertexBuffer.UVKind);
  61457. defines.push("#define UV1");
  61458. }
  61459. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61460. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61461. defines.push("#define UV2");
  61462. }
  61463. }
  61464. // Bones
  61465. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61466. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61467. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61468. if (mesh.numBoneInfluencers > 4) {
  61469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61471. }
  61472. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61473. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61474. }
  61475. else {
  61476. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61477. }
  61478. // Instances
  61479. if (useInstances) {
  61480. defines.push("#define INSTANCES");
  61481. attribs.push("world0");
  61482. attribs.push("world1");
  61483. attribs.push("world2");
  61484. attribs.push("world3");
  61485. }
  61486. // Get correct effect
  61487. var join = defines.join("\n");
  61488. if (this._cachedDefines !== join) {
  61489. this._cachedDefines = join;
  61490. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  61491. }
  61492. return this._effect.isReady();
  61493. };
  61494. DepthRenderer.prototype.getDepthMap = function () {
  61495. return this._depthMap;
  61496. };
  61497. // Methods
  61498. DepthRenderer.prototype.dispose = function () {
  61499. this._depthMap.dispose();
  61500. };
  61501. return DepthRenderer;
  61502. }());
  61503. BABYLON.DepthRenderer = DepthRenderer;
  61504. })(BABYLON || (BABYLON = {}));
  61505. //# sourceMappingURL=babylon.depthRenderer.js.map
  61506. var BABYLON;
  61507. (function (BABYLON) {
  61508. var SSAORenderingPipeline = /** @class */ (function (_super) {
  61509. __extends(SSAORenderingPipeline, _super);
  61510. /**
  61511. * @constructor
  61512. * @param {string} name - The rendering pipeline name
  61513. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61514. * @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 }
  61515. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61516. */
  61517. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  61518. var _this = _super.call(this, scene.getEngine(), name) || this;
  61519. // Members
  61520. /**
  61521. * The PassPostProcess id in the pipeline that contains the original scene color
  61522. * @type {string}
  61523. */
  61524. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61525. /**
  61526. * The SSAO PostProcess id in the pipeline
  61527. * @type {string}
  61528. */
  61529. _this.SSAORenderEffect = "SSAORenderEffect";
  61530. /**
  61531. * The horizontal blur PostProcess id in the pipeline
  61532. * @type {string}
  61533. */
  61534. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61535. /**
  61536. * The vertical blur PostProcess id in the pipeline
  61537. * @type {string}
  61538. */
  61539. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61540. /**
  61541. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61542. * @type {string}
  61543. */
  61544. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61545. /**
  61546. * The output strength of the SSAO post-process. Default value is 1.0.
  61547. * @type {number}
  61548. */
  61549. _this.totalStrength = 1.0;
  61550. /**
  61551. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  61552. * @type {number}
  61553. */
  61554. _this.radius = 0.0001;
  61555. /**
  61556. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  61557. * Must not be equal to fallOff and superior to fallOff.
  61558. * Default value is 0.975
  61559. * @type {number}
  61560. */
  61561. _this.area = 0.0075;
  61562. /**
  61563. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  61564. * Must not be equal to area and inferior to area.
  61565. * Default value is 0.0
  61566. * @type {number}
  61567. */
  61568. _this.fallOff = 0.000001;
  61569. /**
  61570. * The base color of the SSAO post-process
  61571. * The final result is "base + ssao" between [0, 1]
  61572. * @type {number}
  61573. */
  61574. _this.base = 0.5;
  61575. _this._firstUpdate = true;
  61576. _this._scene = scene;
  61577. // Set up assets
  61578. _this._createRandomTexture();
  61579. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  61580. var ssaoRatio = ratio.ssaoRatio || ratio;
  61581. var combineRatio = ratio.combineRatio || ratio;
  61582. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61583. _this._createSSAOPostProcess(ssaoRatio);
  61584. _this._createBlurPostProcess(ssaoRatio);
  61585. _this._createSSAOCombinePostProcess(combineRatio);
  61586. // Set up pipeline
  61587. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61588. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61589. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61590. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  61592. // Finish
  61593. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61594. if (cameras)
  61595. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61596. return _this;
  61597. }
  61598. // Public Methods
  61599. /**
  61600. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  61601. */
  61602. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  61603. if (disableDepthRender === void 0) { disableDepthRender = false; }
  61604. for (var i = 0; i < this._scene.cameras.length; i++) {
  61605. var camera = this._scene.cameras[i];
  61606. this._originalColorPostProcess.dispose(camera);
  61607. this._ssaoPostProcess.dispose(camera);
  61608. this._blurHPostProcess.dispose(camera);
  61609. this._blurVPostProcess.dispose(camera);
  61610. this._ssaoCombinePostProcess.dispose(camera);
  61611. }
  61612. this._randomTexture.dispose();
  61613. if (disableDepthRender)
  61614. this._scene.disableDepthRenderer();
  61615. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  61616. _super.prototype.dispose.call(this);
  61617. };
  61618. // Private Methods
  61619. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  61620. var _this = this;
  61621. var size = 16;
  61622. 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);
  61623. 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);
  61624. this._blurHPostProcess.onActivateObservable.add(function () {
  61625. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  61626. _this._blurHPostProcess.kernel = size * dw;
  61627. });
  61628. this._blurVPostProcess.onActivateObservable.add(function () {
  61629. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  61630. _this._blurVPostProcess.kernel = size * dw;
  61631. });
  61632. };
  61633. SSAORenderingPipeline.prototype._rebuild = function () {
  61634. this._firstUpdate = true;
  61635. _super.prototype._rebuild.call(this);
  61636. };
  61637. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  61638. var _this = this;
  61639. var numSamples = 16;
  61640. var sampleSphere = [
  61641. 0.5381, 0.1856, -0.4319,
  61642. 0.1379, 0.2486, 0.4430,
  61643. 0.3371, 0.5679, -0.0057,
  61644. -0.6999, -0.0451, -0.0019,
  61645. 0.0689, -0.1598, -0.8547,
  61646. 0.0560, 0.0069, -0.1843,
  61647. -0.0146, 0.1402, 0.0762,
  61648. 0.0100, -0.1924, -0.0344,
  61649. -0.3577, -0.5301, -0.4358,
  61650. -0.3169, 0.1063, 0.0158,
  61651. 0.0103, -0.5869, 0.0046,
  61652. -0.0897, -0.4940, 0.3287,
  61653. 0.7119, -0.0154, -0.0918,
  61654. -0.0533, 0.0596, -0.5411,
  61655. 0.0352, -0.0631, 0.5460,
  61656. -0.4776, 0.2847, -0.0271
  61657. ];
  61658. var samplesFactor = 1.0 / numSamples;
  61659. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  61660. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  61661. "area", "fallOff", "base", "range", "viewport"
  61662. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  61663. this._ssaoPostProcess.onApply = function (effect) {
  61664. if (_this._firstUpdate) {
  61665. effect.setArray3("sampleSphere", sampleSphere);
  61666. effect.setFloat("samplesFactor", samplesFactor);
  61667. effect.setFloat("randTextureTiles", 4.0);
  61668. }
  61669. effect.setFloat("totalStrength", _this.totalStrength);
  61670. effect.setFloat("radius", _this.radius);
  61671. effect.setFloat("area", _this.area);
  61672. effect.setFloat("fallOff", _this.fallOff);
  61673. effect.setFloat("base", _this.base);
  61674. effect.setTexture("textureSampler", _this._depthTexture);
  61675. effect.setTexture("randomSampler", _this._randomTexture);
  61676. };
  61677. };
  61678. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  61679. var _this = this;
  61680. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  61681. this._ssaoCombinePostProcess.onApply = function (effect) {
  61682. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  61683. };
  61684. };
  61685. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  61686. var size = 512;
  61687. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61688. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61689. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61690. var context = this._randomTexture.getContext();
  61691. var rand = function (min, max) {
  61692. return Math.random() * (max - min) + min;
  61693. };
  61694. var randVector = BABYLON.Vector3.Zero();
  61695. for (var x = 0; x < size; x++) {
  61696. for (var y = 0; y < size; y++) {
  61697. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  61698. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  61699. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  61700. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  61701. context.fillRect(x, y, 1, 1);
  61702. }
  61703. }
  61704. this._randomTexture.update(false);
  61705. };
  61706. __decorate([
  61707. BABYLON.serialize()
  61708. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  61709. __decorate([
  61710. BABYLON.serialize()
  61711. ], SSAORenderingPipeline.prototype, "radius", void 0);
  61712. __decorate([
  61713. BABYLON.serialize()
  61714. ], SSAORenderingPipeline.prototype, "area", void 0);
  61715. __decorate([
  61716. BABYLON.serialize()
  61717. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  61718. __decorate([
  61719. BABYLON.serialize()
  61720. ], SSAORenderingPipeline.prototype, "base", void 0);
  61721. return SSAORenderingPipeline;
  61722. }(BABYLON.PostProcessRenderPipeline));
  61723. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  61724. })(BABYLON || (BABYLON = {}));
  61725. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  61726. var BABYLON;
  61727. (function (BABYLON) {
  61728. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  61729. __extends(SSAO2RenderingPipeline, _super);
  61730. /**
  61731. * @constructor
  61732. * @param {string} name - The rendering pipeline name
  61733. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61734. * @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 }
  61735. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61736. */
  61737. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  61738. var _this = _super.call(this, scene.getEngine(), name) || this;
  61739. // Members
  61740. /**
  61741. * The PassPostProcess id in the pipeline that contains the original scene color
  61742. * @type {string}
  61743. */
  61744. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61745. /**
  61746. * The SSAO PostProcess id in the pipeline
  61747. * @type {string}
  61748. */
  61749. _this.SSAORenderEffect = "SSAORenderEffect";
  61750. /**
  61751. * The horizontal blur PostProcess id in the pipeline
  61752. * @type {string}
  61753. */
  61754. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61755. /**
  61756. * The vertical blur PostProcess id in the pipeline
  61757. * @type {string}
  61758. */
  61759. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61760. /**
  61761. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61762. * @type {string}
  61763. */
  61764. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61765. /**
  61766. * The output strength of the SSAO post-process. Default value is 1.0.
  61767. * @type {number}
  61768. */
  61769. _this.totalStrength = 1.0;
  61770. /**
  61771. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  61772. * @type {number}
  61773. */
  61774. _this.maxZ = 100.0;
  61775. /**
  61776. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  61777. * @type {number}
  61778. */
  61779. _this.minZAspect = 0.2;
  61780. /**
  61781. * Number of samples used for the SSAO calculations. Default value is 8
  61782. * @type {number}
  61783. */
  61784. _this._samples = 8;
  61785. /**
  61786. * Are we using bilateral blur ?
  61787. * @type {boolean}
  61788. */
  61789. _this._expensiveBlur = true;
  61790. /**
  61791. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  61792. * @type {number}
  61793. */
  61794. _this.radius = 2.0;
  61795. /**
  61796. * The base color of the SSAO post-process
  61797. * The final result is "base + ssao" between [0, 1]
  61798. * @type {number}
  61799. */
  61800. _this.base = 0.1;
  61801. _this._firstUpdate = true;
  61802. _this._scene = scene;
  61803. if (!_this.isSupported) {
  61804. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  61805. return _this;
  61806. }
  61807. var ssaoRatio = ratio.ssaoRatio || ratio;
  61808. var blurRatio = ratio.blurRatio || ratio;
  61809. // Set up assets
  61810. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  61811. _this._createRandomTexture();
  61812. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  61813. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  61814. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  61815. _this._createSSAOPostProcess(1.0);
  61816. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  61817. _this._createSSAOCombinePostProcess(blurRatio);
  61818. // Set up pipeline
  61819. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  61820. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  61821. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  61822. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  61823. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  61824. // Finish
  61825. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61826. if (cameras)
  61827. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61828. return _this;
  61829. }
  61830. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  61831. get: function () {
  61832. return this._samples;
  61833. },
  61834. set: function (n) {
  61835. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  61836. this._samples = n;
  61837. this._sampleSphere = this._generateHemisphere();
  61838. this._firstUpdate = true;
  61839. },
  61840. enumerable: true,
  61841. configurable: true
  61842. });
  61843. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  61844. get: function () {
  61845. return this._expensiveBlur;
  61846. },
  61847. set: function (b) {
  61848. 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"]);
  61849. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  61850. this._expensiveBlur = b;
  61851. this._firstUpdate = true;
  61852. },
  61853. enumerable: true,
  61854. configurable: true
  61855. });
  61856. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  61857. /**
  61858. * Support test.
  61859. * @type {boolean}
  61860. */
  61861. get: function () {
  61862. var engine = BABYLON.Engine.LastCreatedEngine;
  61863. if (!engine) {
  61864. return false;
  61865. }
  61866. return engine.getCaps().drawBuffersExtension;
  61867. },
  61868. enumerable: true,
  61869. configurable: true
  61870. });
  61871. // Public Methods
  61872. /**
  61873. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  61874. */
  61875. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  61876. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  61877. for (var i = 0; i < this._scene.cameras.length; i++) {
  61878. var camera = this._scene.cameras[i];
  61879. this._originalColorPostProcess.dispose(camera);
  61880. this._ssaoPostProcess.dispose(camera);
  61881. this._blurHPostProcess.dispose(camera);
  61882. this._blurVPostProcess.dispose(camera);
  61883. this._ssaoCombinePostProcess.dispose(camera);
  61884. }
  61885. this._randomTexture.dispose();
  61886. if (disableGeometryBufferRenderer)
  61887. this._scene.disableGeometryBufferRenderer();
  61888. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  61889. _super.prototype.dispose.call(this);
  61890. };
  61891. // Private Methods
  61892. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  61893. var _this = this;
  61894. this._samplerOffsets = [];
  61895. var expensive = this.expensiveBlur;
  61896. for (var i = -8; i < 8; i++) {
  61897. this._samplerOffsets.push(i * 2 + 0.5);
  61898. }
  61899. 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");
  61900. this._blurHPostProcess.onApply = function (effect) {
  61901. if (!_this._scene.activeCamera) {
  61902. return;
  61903. }
  61904. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  61905. effect.setFloat("near", _this._scene.activeCamera.minZ);
  61906. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  61907. effect.setFloat("radius", _this.radius);
  61908. effect.setTexture("depthSampler", _this._depthTexture);
  61909. if (_this._firstUpdate) {
  61910. effect.setArray("samplerOffsets", _this._samplerOffsets);
  61911. }
  61912. };
  61913. 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");
  61914. this._blurVPostProcess.onApply = function (effect) {
  61915. if (!_this._scene.activeCamera) {
  61916. return;
  61917. }
  61918. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  61919. effect.setFloat("near", _this._scene.activeCamera.minZ);
  61920. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  61921. effect.setFloat("radius", _this.radius);
  61922. effect.setTexture("depthSampler", _this._depthTexture);
  61923. if (_this._firstUpdate) {
  61924. effect.setArray("samplerOffsets", _this._samplerOffsets);
  61925. _this._firstUpdate = false;
  61926. }
  61927. };
  61928. };
  61929. SSAO2RenderingPipeline.prototype._rebuild = function () {
  61930. this._firstUpdate = true;
  61931. _super.prototype._rebuild.call(this);
  61932. };
  61933. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  61934. var numSamples = this.samples;
  61935. var result = [];
  61936. var vector, scale;
  61937. var rand = function (min, max) {
  61938. return Math.random() * (max - min) + min;
  61939. };
  61940. var i = 0;
  61941. while (i < numSamples) {
  61942. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  61943. vector.normalize();
  61944. scale = i / numSamples;
  61945. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  61946. vector.scaleInPlace(scale);
  61947. result.push(vector.x, vector.y, vector.z);
  61948. i++;
  61949. }
  61950. return result;
  61951. };
  61952. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  61953. var _this = this;
  61954. var numSamples = this.samples;
  61955. this._sampleSphere = this._generateHemisphere();
  61956. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  61957. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  61958. "base", "range", "projection", "near", "far", "texelSize",
  61959. "xViewport", "yViewport", "maxZ", "minZAspect"
  61960. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  61961. this._ssaoPostProcess.onApply = function (effect) {
  61962. if (_this._firstUpdate) {
  61963. effect.setArray3("sampleSphere", _this._sampleSphere);
  61964. effect.setFloat("randTextureTiles", 4.0);
  61965. }
  61966. if (!_this._scene.activeCamera) {
  61967. return;
  61968. }
  61969. effect.setFloat("samplesFactor", 1 / _this.samples);
  61970. effect.setFloat("totalStrength", _this.totalStrength);
  61971. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  61972. effect.setFloat("radius", _this.radius);
  61973. effect.setFloat("maxZ", _this.maxZ);
  61974. effect.setFloat("minZAspect", _this.minZAspect);
  61975. effect.setFloat("base", _this.base);
  61976. effect.setFloat("near", _this._scene.activeCamera.minZ);
  61977. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  61978. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  61979. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  61980. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  61981. effect.setTexture("textureSampler", _this._depthTexture);
  61982. effect.setTexture("normalSampler", _this._normalTexture);
  61983. effect.setTexture("randomSampler", _this._randomTexture);
  61984. };
  61985. };
  61986. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  61987. var _this = this;
  61988. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  61989. this._ssaoCombinePostProcess.onApply = function (effect) {
  61990. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  61991. };
  61992. };
  61993. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  61994. var size = 512;
  61995. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61996. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  61997. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  61998. var context = this._randomTexture.getContext();
  61999. var rand = function (min, max) {
  62000. return Math.random() * (max - min) + min;
  62001. };
  62002. var randVector = BABYLON.Vector3.Zero();
  62003. for (var x = 0; x < size; x++) {
  62004. for (var y = 0; y < size; y++) {
  62005. randVector.x = rand(0.0, 1.0);
  62006. randVector.y = rand(0.0, 1.0);
  62007. randVector.z = 0.0;
  62008. randVector.normalize();
  62009. randVector.scaleInPlace(255);
  62010. randVector.x = Math.floor(randVector.x);
  62011. randVector.y = Math.floor(randVector.y);
  62012. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62013. context.fillRect(x, y, 1, 1);
  62014. }
  62015. }
  62016. this._randomTexture.update(false);
  62017. };
  62018. __decorate([
  62019. BABYLON.serialize()
  62020. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62021. __decorate([
  62022. BABYLON.serialize()
  62023. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62024. __decorate([
  62025. BABYLON.serialize()
  62026. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62027. __decorate([
  62028. BABYLON.serialize("samples")
  62029. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62030. __decorate([
  62031. BABYLON.serialize("expensiveBlur")
  62032. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62033. __decorate([
  62034. BABYLON.serialize()
  62035. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62036. __decorate([
  62037. BABYLON.serialize()
  62038. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62039. return SSAO2RenderingPipeline;
  62040. }(BABYLON.PostProcessRenderPipeline));
  62041. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62042. })(BABYLON || (BABYLON = {}));
  62043. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62044. // BABYLON.JS Chromatic Aberration GLSL Shader
  62045. // Author: Olivier Guyot
  62046. // Separates very slightly R, G and B colors on the edges of the screen
  62047. // Inspired by Francois Tarlier & Martins Upitis
  62048. var BABYLON;
  62049. (function (BABYLON) {
  62050. var LensRenderingPipeline = /** @class */ (function (_super) {
  62051. __extends(LensRenderingPipeline, _super);
  62052. /**
  62053. * @constructor
  62054. *
  62055. * Effect parameters are as follow:
  62056. * {
  62057. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62058. * edge_blur: number; // from 0 to x (1 for realism)
  62059. * distortion: number; // from 0 to x (1 for realism)
  62060. * grain_amount: number; // from 0 to 1
  62061. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62062. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62063. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62064. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62065. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62066. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62067. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62068. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62069. * }
  62070. * Note: if an effect parameter is unset, effect is disabled
  62071. *
  62072. * @param {string} name - The rendering pipeline name
  62073. * @param {object} parameters - An object containing all parameters (see above)
  62074. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62075. * @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)
  62076. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62077. */
  62078. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62079. if (ratio === void 0) { ratio = 1.0; }
  62080. var _this = _super.call(this, scene.getEngine(), name) || this;
  62081. // Lens effects can be of the following:
  62082. // - chromatic aberration (slight shift of RGB colors)
  62083. // - blur on the edge of the lens
  62084. // - lens distortion
  62085. // - depth-of-field blur & highlights enhancing
  62086. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62087. // - grain effect (noise or custom texture)
  62088. // Two additional texture samplers are needed:
  62089. // - depth map (for depth-of-field)
  62090. // - grain texture
  62091. /**
  62092. * The chromatic aberration PostProcess id in the pipeline
  62093. * @type {string}
  62094. */
  62095. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62096. /**
  62097. * The highlights enhancing PostProcess id in the pipeline
  62098. * @type {string}
  62099. */
  62100. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62101. /**
  62102. * The depth-of-field PostProcess id in the pipeline
  62103. * @type {string}
  62104. */
  62105. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62106. _this._scene = scene;
  62107. // Fetch texture samplers
  62108. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62109. if (parameters.grain_texture) {
  62110. _this._grainTexture = parameters.grain_texture;
  62111. }
  62112. else {
  62113. _this._createGrainTexture();
  62114. }
  62115. // save parameters
  62116. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62117. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62118. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62119. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62120. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62121. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62122. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62123. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62124. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62125. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62126. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62127. // Create effects
  62128. _this._createChromaticAberrationPostProcess(ratio);
  62129. _this._createHighlightsPostProcess(ratio);
  62130. _this._createDepthOfFieldPostProcess(ratio / 4);
  62131. // Set up pipeline
  62132. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62133. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62134. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62135. if (_this._highlightsGain === -1) {
  62136. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62137. }
  62138. // Finish
  62139. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62140. if (cameras) {
  62141. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62142. }
  62143. return _this;
  62144. }
  62145. // public methods (self explanatory)
  62146. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62147. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62148. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62149. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62150. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62151. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62152. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62153. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62154. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62155. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62156. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62157. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62158. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62159. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62160. };
  62161. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62162. this._highlightsPostProcess.updateEffect();
  62163. };
  62164. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62165. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62166. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62167. this._highlightsGain = amount;
  62168. };
  62169. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62170. if (this._highlightsGain === -1) {
  62171. this._highlightsGain = 1.0;
  62172. }
  62173. this._highlightsThreshold = amount;
  62174. };
  62175. LensRenderingPipeline.prototype.disableHighlights = function () {
  62176. this._highlightsGain = -1;
  62177. };
  62178. /**
  62179. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62180. */
  62181. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62182. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62183. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62184. this._chromaticAberrationPostProcess = null;
  62185. this._highlightsPostProcess = null;
  62186. this._depthOfFieldPostProcess = null;
  62187. this._grainTexture.dispose();
  62188. if (disableDepthRender)
  62189. this._scene.disableDepthRenderer();
  62190. };
  62191. // colors shifting and distortion
  62192. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62193. var _this = this;
  62194. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62195. [], // samplers
  62196. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62197. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62198. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62199. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62200. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62201. };
  62202. };
  62203. // highlights enhancing
  62204. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62205. var _this = this;
  62206. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62207. [], // samplers
  62208. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62209. this._highlightsPostProcess.onApply = function (effect) {
  62210. effect.setFloat('gain', _this._highlightsGain);
  62211. effect.setFloat('threshold', _this._highlightsThreshold);
  62212. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62213. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62214. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62215. };
  62216. };
  62217. // colors shifting and distortion
  62218. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62219. var _this = this;
  62220. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62221. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62222. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62223. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62224. this._depthOfFieldPostProcess.onApply = function (effect) {
  62225. effect.setTexture("depthSampler", _this._depthTexture);
  62226. effect.setTexture("grainSampler", _this._grainTexture);
  62227. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62228. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62229. effect.setFloat('grain_amount', _this._grainAmount);
  62230. effect.setBool('blur_noise', _this._blurNoise);
  62231. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62232. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62233. effect.setFloat('distortion', _this._distortion);
  62234. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  62235. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  62236. effect.setFloat('aperture', _this._dofAperture);
  62237. effect.setFloat('darken', _this._dofDarken);
  62238. effect.setFloat('edge_blur', _this._edgeBlur);
  62239. effect.setBool('highlights', (_this._highlightsGain !== -1));
  62240. if (_this._scene.activeCamera) {
  62241. effect.setFloat('near', _this._scene.activeCamera.minZ);
  62242. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  62243. }
  62244. };
  62245. };
  62246. // creates a black and white random noise texture, 512x512
  62247. LensRenderingPipeline.prototype._createGrainTexture = function () {
  62248. var size = 512;
  62249. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62250. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62251. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62252. var context = this._grainTexture.getContext();
  62253. var rand = function (min, max) {
  62254. return Math.random() * (max - min) + min;
  62255. };
  62256. var value;
  62257. for (var x = 0; x < size; x++) {
  62258. for (var y = 0; y < size; y++) {
  62259. value = Math.floor(rand(0.42, 0.58) * 255);
  62260. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  62261. context.fillRect(x, y, 1, 1);
  62262. }
  62263. }
  62264. this._grainTexture.update(false);
  62265. };
  62266. return LensRenderingPipeline;
  62267. }(BABYLON.PostProcessRenderPipeline));
  62268. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  62269. })(BABYLON || (BABYLON = {}));
  62270. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  62271. var BABYLON;
  62272. (function (BABYLON) {
  62273. var StandardRenderingPipeline = /** @class */ (function (_super) {
  62274. __extends(StandardRenderingPipeline, _super);
  62275. /**
  62276. * @constructor
  62277. * @param {string} name - The rendering pipeline name
  62278. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62279. * @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)
  62280. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62281. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62282. */
  62283. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62284. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62285. var _this = _super.call(this, scene.getEngine(), name) || this;
  62286. _this.downSampleX4PostProcess = null;
  62287. _this.brightPassPostProcess = null;
  62288. _this.blurHPostProcesses = [];
  62289. _this.blurVPostProcesses = [];
  62290. _this.textureAdderPostProcess = null;
  62291. _this.volumetricLightPostProcess = null;
  62292. _this.volumetricLightSmoothXPostProcess = null;
  62293. _this.volumetricLightSmoothYPostProcess = null;
  62294. _this.volumetricLightMergePostProces = null;
  62295. _this.volumetricLightFinalPostProcess = null;
  62296. _this.luminancePostProcess = null;
  62297. _this.luminanceDownSamplePostProcesses = [];
  62298. _this.hdrPostProcess = null;
  62299. _this.textureAdderFinalPostProcess = null;
  62300. _this.lensFlareFinalPostProcess = null;
  62301. _this.hdrFinalPostProcess = null;
  62302. _this.lensFlarePostProcess = null;
  62303. _this.lensFlareComposePostProcess = null;
  62304. _this.motionBlurPostProcess = null;
  62305. _this.depthOfFieldPostProcess = null;
  62306. // Values
  62307. _this.brightThreshold = 1.0;
  62308. _this.blurWidth = 512.0;
  62309. _this.horizontalBlur = false;
  62310. _this.exposure = 1.0;
  62311. _this.lensTexture = null;
  62312. _this.volumetricLightCoefficient = 0.2;
  62313. _this.volumetricLightPower = 4.0;
  62314. _this.volumetricLightBlurScale = 64.0;
  62315. _this.sourceLight = null;
  62316. _this.hdrMinimumLuminance = 1.0;
  62317. _this.hdrDecreaseRate = 0.5;
  62318. _this.hdrIncreaseRate = 0.5;
  62319. _this.lensColorTexture = null;
  62320. _this.lensFlareStrength = 20.0;
  62321. _this.lensFlareGhostDispersal = 1.4;
  62322. _this.lensFlareHaloWidth = 0.7;
  62323. _this.lensFlareDistortionStrength = 16.0;
  62324. _this.lensStarTexture = null;
  62325. _this.lensFlareDirtTexture = null;
  62326. _this.depthOfFieldDistance = 10.0;
  62327. _this.depthOfFieldBlurWidth = 64.0;
  62328. _this.motionStrength = 1.0;
  62329. // IAnimatable
  62330. _this.animations = [];
  62331. _this._currentDepthOfFieldSource = null;
  62332. _this._hdrCurrentLuminance = 1.0;
  62333. // Getters and setters
  62334. _this._bloomEnabled = true;
  62335. _this._depthOfFieldEnabled = false;
  62336. _this._vlsEnabled = false;
  62337. _this._lensFlareEnabled = false;
  62338. _this._hdrEnabled = false;
  62339. _this._motionBlurEnabled = false;
  62340. _this._motionBlurSamples = 64.0;
  62341. _this._volumetricLightStepsCount = 50.0;
  62342. _this._cameras = cameras || [];
  62343. // Initialize
  62344. _this._scene = scene;
  62345. _this._basePostProcess = originalPostProcess;
  62346. _this._ratio = ratio;
  62347. // Misc
  62348. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62349. // Finish
  62350. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62351. _this._buildPipeline();
  62352. return _this;
  62353. }
  62354. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  62355. get: function () {
  62356. return this._bloomEnabled;
  62357. },
  62358. set: function (enabled) {
  62359. if (this._bloomEnabled === enabled) {
  62360. return;
  62361. }
  62362. this._bloomEnabled = enabled;
  62363. this._buildPipeline();
  62364. },
  62365. enumerable: true,
  62366. configurable: true
  62367. });
  62368. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62369. get: function () {
  62370. return this._depthOfFieldEnabled;
  62371. },
  62372. set: function (enabled) {
  62373. if (this._depthOfFieldEnabled === enabled) {
  62374. return;
  62375. }
  62376. this._depthOfFieldEnabled = enabled;
  62377. this._buildPipeline();
  62378. },
  62379. enumerable: true,
  62380. configurable: true
  62381. });
  62382. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  62383. get: function () {
  62384. return this._lensFlareEnabled;
  62385. },
  62386. set: function (enabled) {
  62387. if (this._lensFlareEnabled === enabled) {
  62388. return;
  62389. }
  62390. this._lensFlareEnabled = enabled;
  62391. this._buildPipeline();
  62392. },
  62393. enumerable: true,
  62394. configurable: true
  62395. });
  62396. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  62397. get: function () {
  62398. return this._hdrEnabled;
  62399. },
  62400. set: function (enabled) {
  62401. if (this._hdrEnabled === enabled) {
  62402. return;
  62403. }
  62404. this._hdrEnabled = enabled;
  62405. this._buildPipeline();
  62406. },
  62407. enumerable: true,
  62408. configurable: true
  62409. });
  62410. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  62411. get: function () {
  62412. return this._vlsEnabled;
  62413. },
  62414. set: function (enabled) {
  62415. if (this._vlsEnabled === enabled) {
  62416. return;
  62417. }
  62418. if (enabled) {
  62419. var geometry = this._scene.enableGeometryBufferRenderer();
  62420. if (!geometry) {
  62421. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  62422. return;
  62423. }
  62424. }
  62425. this._vlsEnabled = enabled;
  62426. this._buildPipeline();
  62427. },
  62428. enumerable: true,
  62429. configurable: true
  62430. });
  62431. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  62432. get: function () {
  62433. return this._motionBlurEnabled;
  62434. },
  62435. set: function (enabled) {
  62436. if (this._motionBlurEnabled === enabled) {
  62437. return;
  62438. }
  62439. this._motionBlurEnabled = enabled;
  62440. this._buildPipeline();
  62441. },
  62442. enumerable: true,
  62443. configurable: true
  62444. });
  62445. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  62446. get: function () {
  62447. return this._volumetricLightStepsCount;
  62448. },
  62449. set: function (count) {
  62450. if (this.volumetricLightPostProcess) {
  62451. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  62452. }
  62453. this._volumetricLightStepsCount = count;
  62454. },
  62455. enumerable: true,
  62456. configurable: true
  62457. });
  62458. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  62459. get: function () {
  62460. return this._motionBlurSamples;
  62461. },
  62462. set: function (samples) {
  62463. if (this.motionBlurPostProcess) {
  62464. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  62465. }
  62466. this._motionBlurSamples = samples;
  62467. },
  62468. enumerable: true,
  62469. configurable: true
  62470. });
  62471. StandardRenderingPipeline.prototype._buildPipeline = function () {
  62472. var _this = this;
  62473. var ratio = this._ratio;
  62474. var scene = this._scene;
  62475. this._disposePostProcesses();
  62476. this._reset();
  62477. // Create pass post-process
  62478. if (!this._basePostProcess) {
  62479. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  62480. this.originalPostProcess.onApply = function (effect) {
  62481. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  62482. };
  62483. }
  62484. else {
  62485. this.originalPostProcess = this._basePostProcess;
  62486. }
  62487. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  62488. this._currentDepthOfFieldSource = this.originalPostProcess;
  62489. if (this._vlsEnabled) {
  62490. // Create volumetric light
  62491. this._createVolumetricLightPostProcess(scene, ratio);
  62492. // Create volumetric light final post-process
  62493. 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);
  62494. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  62495. }
  62496. if (this._bloomEnabled) {
  62497. // Create down sample X4 post-process
  62498. this._createDownSampleX4PostProcess(scene, ratio / 2);
  62499. // Create bright pass post-process
  62500. this._createBrightPassPostProcess(scene, ratio / 2);
  62501. // Create gaussian blur post-processes (down sampling blurs)
  62502. this._createBlurPostProcesses(scene, ratio / 4, 1);
  62503. // Create texture adder post-process
  62504. this._createTextureAdderPostProcess(scene, ratio);
  62505. // Create depth-of-field source post-process
  62506. 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);
  62507. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  62508. }
  62509. if (this._lensFlareEnabled) {
  62510. // Create lens flare post-process
  62511. this._createLensFlarePostProcess(scene, ratio);
  62512. // Create depth-of-field source post-process post lens-flare and disable it now
  62513. 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);
  62514. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  62515. }
  62516. if (this._hdrEnabled) {
  62517. // Create luminance
  62518. this._createLuminancePostProcesses(scene, this._floatTextureType);
  62519. // Create HDR
  62520. this._createHdrPostProcess(scene, ratio);
  62521. // Create depth-of-field source post-process post hdr and disable it now
  62522. 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);
  62523. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  62524. }
  62525. if (this._depthOfFieldEnabled) {
  62526. // Create gaussian blur used by depth-of-field
  62527. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  62528. // Create depth-of-field post-process
  62529. this._createDepthOfFieldPostProcess(scene, ratio);
  62530. }
  62531. if (this._motionBlurEnabled) {
  62532. // Create motion blur post-process
  62533. this._createMotionBlurPostProcess(scene, ratio);
  62534. }
  62535. if (this._cameras !== null) {
  62536. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  62537. }
  62538. };
  62539. // Down Sample X4 Post-Processs
  62540. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  62541. var _this = this;
  62542. var downSampleX4Offsets = new Array(32);
  62543. 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);
  62544. this.downSampleX4PostProcess.onApply = function (effect) {
  62545. var id = 0;
  62546. var width = _this.downSampleX4PostProcess.width;
  62547. var height = _this.downSampleX4PostProcess.height;
  62548. for (var i = -2; i < 2; i++) {
  62549. for (var j = -2; j < 2; j++) {
  62550. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  62551. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  62552. id += 2;
  62553. }
  62554. }
  62555. effect.setArray2("dsOffsets", downSampleX4Offsets);
  62556. };
  62557. // Add to pipeline
  62558. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  62559. };
  62560. // Brightpass Post-Process
  62561. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  62562. var _this = this;
  62563. var brightOffsets = new Array(8);
  62564. 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);
  62565. this.brightPassPostProcess.onApply = function (effect) {
  62566. var sU = (1.0 / _this.brightPassPostProcess.width);
  62567. var sV = (1.0 / _this.brightPassPostProcess.height);
  62568. brightOffsets[0] = -0.5 * sU;
  62569. brightOffsets[1] = 0.5 * sV;
  62570. brightOffsets[2] = 0.5 * sU;
  62571. brightOffsets[3] = 0.5 * sV;
  62572. brightOffsets[4] = -0.5 * sU;
  62573. brightOffsets[5] = -0.5 * sV;
  62574. brightOffsets[6] = 0.5 * sU;
  62575. brightOffsets[7] = -0.5 * sV;
  62576. effect.setArray2("dsOffsets", brightOffsets);
  62577. effect.setFloat("brightThreshold", _this.brightThreshold);
  62578. };
  62579. // Add to pipeline
  62580. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  62581. };
  62582. // Create blur H&V post-processes
  62583. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  62584. var _this = this;
  62585. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  62586. var engine = scene.getEngine();
  62587. 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);
  62588. 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);
  62589. blurX.onActivateObservable.add(function () {
  62590. var dw = blurX.width / engine.getRenderWidth();
  62591. blurX.kernel = _this[blurWidthKey] * dw;
  62592. });
  62593. blurY.onActivateObservable.add(function () {
  62594. var dw = blurY.height / engine.getRenderHeight();
  62595. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  62596. });
  62597. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  62598. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  62599. this.blurHPostProcesses.push(blurX);
  62600. this.blurVPostProcesses.push(blurY);
  62601. };
  62602. // Create texture adder post-process
  62603. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62604. var _this = this;
  62605. 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);
  62606. this.textureAdderPostProcess.onApply = function (effect) {
  62607. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  62608. effect.setTexture("lensSampler", _this.lensTexture);
  62609. effect.setFloat("exposure", _this.exposure);
  62610. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  62611. };
  62612. // Add to pipeline
  62613. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62614. };
  62615. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  62616. var _this = this;
  62617. var geometryRenderer = scene.enableGeometryBufferRenderer();
  62618. geometryRenderer.enablePosition = true;
  62619. var geometry = geometryRenderer.getGBuffer();
  62620. // Base post-process
  62621. 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));
  62622. var depthValues = BABYLON.Vector2.Zero();
  62623. this.volumetricLightPostProcess.onApply = function (effect) {
  62624. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  62625. var generator = _this.sourceLight.getShadowGenerator();
  62626. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  62627. effect.setTexture("positionSampler", geometry.textures[2]);
  62628. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  62629. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  62630. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  62631. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  62632. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  62633. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  62634. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  62635. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  62636. effect.setVector2("depthValues", depthValues);
  62637. }
  62638. };
  62639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  62640. // Smooth
  62641. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  62642. // Merge
  62643. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  62644. this.volumetricLightMergePostProces.onApply = function (effect) {
  62645. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  62646. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  62647. };
  62648. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  62649. };
  62650. // Create luminance
  62651. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  62652. var _this = this;
  62653. // Create luminance
  62654. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  62655. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  62656. var offsets = [];
  62657. this.luminancePostProcess.onApply = function (effect) {
  62658. var sU = (1.0 / _this.luminancePostProcess.width);
  62659. var sV = (1.0 / _this.luminancePostProcess.height);
  62660. offsets[0] = -0.5 * sU;
  62661. offsets[1] = 0.5 * sV;
  62662. offsets[2] = 0.5 * sU;
  62663. offsets[3] = 0.5 * sV;
  62664. offsets[4] = -0.5 * sU;
  62665. offsets[5] = -0.5 * sV;
  62666. offsets[6] = 0.5 * sU;
  62667. offsets[7] = -0.5 * sV;
  62668. effect.setArray2("lumOffsets", offsets);
  62669. };
  62670. // Add to pipeline
  62671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  62672. // Create down sample luminance
  62673. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  62674. var size = Math.pow(3, i);
  62675. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  62676. if (i === 0) {
  62677. defines += "#define FINAL_DOWN_SAMPLER";
  62678. }
  62679. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  62680. this.luminanceDownSamplePostProcesses.push(postProcess);
  62681. }
  62682. // Create callbacks and add effects
  62683. var lastLuminance = this.luminancePostProcess;
  62684. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  62685. var downSampleOffsets = new Array(18);
  62686. pp.onApply = function (effect) {
  62687. if (!lastLuminance) {
  62688. return;
  62689. }
  62690. var id = 0;
  62691. for (var x = -1; x < 2; x++) {
  62692. for (var y = -1; y < 2; y++) {
  62693. downSampleOffsets[id] = x / lastLuminance.width;
  62694. downSampleOffsets[id + 1] = y / lastLuminance.height;
  62695. id += 2;
  62696. }
  62697. }
  62698. effect.setArray2("dsOffsets", downSampleOffsets);
  62699. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  62700. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62701. lastLuminance = _this.luminancePostProcess;
  62702. }
  62703. else {
  62704. lastLuminance = pp;
  62705. }
  62706. };
  62707. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  62708. pp.onAfterRender = function (effect) {
  62709. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  62710. 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);
  62711. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  62712. };
  62713. }
  62714. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  62715. });
  62716. };
  62717. // Create HDR post-process
  62718. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  62719. var _this = this;
  62720. 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);
  62721. var outputLiminance = 1;
  62722. var time = 0;
  62723. var lastTime = 0;
  62724. this.hdrPostProcess.onApply = function (effect) {
  62725. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  62726. time += scene.getEngine().getDeltaTime();
  62727. if (outputLiminance < 0) {
  62728. outputLiminance = _this._hdrCurrentLuminance;
  62729. }
  62730. else {
  62731. var dt = (lastTime - time) / 1000.0;
  62732. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  62733. outputLiminance += _this.hdrDecreaseRate * dt;
  62734. }
  62735. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  62736. outputLiminance -= _this.hdrIncreaseRate * dt;
  62737. }
  62738. else {
  62739. outputLiminance = _this._hdrCurrentLuminance;
  62740. }
  62741. }
  62742. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  62743. effect.setFloat("averageLuminance", outputLiminance);
  62744. lastTime = time;
  62745. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  62746. };
  62747. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  62748. };
  62749. // Create lens flare post-process
  62750. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  62751. var _this = this;
  62752. 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);
  62753. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  62754. this._createBlurPostProcesses(scene, ratio / 4, 2);
  62755. 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);
  62756. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  62757. var resolution = new BABYLON.Vector2(0, 0);
  62758. // Lens flare
  62759. this.lensFlarePostProcess.onApply = function (effect) {
  62760. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  62761. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  62762. effect.setFloat("strength", _this.lensFlareStrength);
  62763. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  62764. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  62765. // Shift
  62766. resolution.x = _this.lensFlarePostProcess.width;
  62767. resolution.y = _this.lensFlarePostProcess.height;
  62768. effect.setVector2("resolution", resolution);
  62769. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  62770. };
  62771. // Compose
  62772. 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);
  62773. 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);
  62774. this.lensFlareComposePostProcess.onApply = function (effect) {
  62775. if (!_this._scene.activeCamera) {
  62776. return;
  62777. }
  62778. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62779. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  62780. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  62781. // Lens start rotation matrix
  62782. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  62783. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  62784. 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));
  62785. camRot *= 4.0;
  62786. 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);
  62787. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  62788. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  62789. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  62790. };
  62791. };
  62792. // Create depth-of-field post-process
  62793. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62794. var _this = this;
  62795. 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);
  62796. this.depthOfFieldPostProcess.onApply = function (effect) {
  62797. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  62798. effect.setTexture("depthSampler", _this._getDepthTexture());
  62799. effect.setFloat("distance", _this.depthOfFieldDistance);
  62800. };
  62801. // Add to pipeline
  62802. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62803. };
  62804. // Create motion blur post-process
  62805. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  62806. var _this = this;
  62807. 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);
  62808. var motionScale = 0;
  62809. var prevViewProjection = BABYLON.Matrix.Identity();
  62810. var invViewProjection = BABYLON.Matrix.Identity();
  62811. var viewProjection = BABYLON.Matrix.Identity();
  62812. var screenSize = BABYLON.Vector2.Zero();
  62813. this.motionBlurPostProcess.onApply = function (effect) {
  62814. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  62815. viewProjection.invertToRef(invViewProjection);
  62816. effect.setMatrix("inverseViewProjection", invViewProjection);
  62817. effect.setMatrix("prevViewProjection", prevViewProjection);
  62818. prevViewProjection = viewProjection;
  62819. screenSize.x = _this.motionBlurPostProcess.width;
  62820. screenSize.y = _this.motionBlurPostProcess.height;
  62821. effect.setVector2("screenSize", screenSize);
  62822. motionScale = scene.getEngine().getFps() / 60.0;
  62823. effect.setFloat("motionScale", motionScale);
  62824. effect.setFloat("motionStrength", _this.motionStrength);
  62825. effect.setTexture("depthSampler", _this._getDepthTexture());
  62826. };
  62827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  62828. };
  62829. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  62830. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  62831. var renderer = this._scene.enableGeometryBufferRenderer();
  62832. return renderer.getGBuffer().textures[0];
  62833. }
  62834. return this._scene.enableDepthRenderer().getDepthMap();
  62835. };
  62836. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  62837. for (var i = 0; i < this._cameras.length; i++) {
  62838. var camera = this._cameras[i];
  62839. if (this.originalPostProcess) {
  62840. this.originalPostProcess.dispose(camera);
  62841. }
  62842. if (this.downSampleX4PostProcess) {
  62843. this.downSampleX4PostProcess.dispose(camera);
  62844. }
  62845. if (this.brightPassPostProcess) {
  62846. this.brightPassPostProcess.dispose(camera);
  62847. }
  62848. if (this.textureAdderPostProcess) {
  62849. this.textureAdderPostProcess.dispose(camera);
  62850. }
  62851. if (this.textureAdderFinalPostProcess) {
  62852. this.textureAdderFinalPostProcess.dispose(camera);
  62853. }
  62854. if (this.volumetricLightPostProcess) {
  62855. this.volumetricLightPostProcess.dispose(camera);
  62856. }
  62857. if (this.volumetricLightSmoothXPostProcess) {
  62858. this.volumetricLightSmoothXPostProcess.dispose(camera);
  62859. }
  62860. if (this.volumetricLightSmoothYPostProcess) {
  62861. this.volumetricLightSmoothYPostProcess.dispose(camera);
  62862. }
  62863. if (this.volumetricLightMergePostProces) {
  62864. this.volumetricLightMergePostProces.dispose(camera);
  62865. }
  62866. if (this.volumetricLightFinalPostProcess) {
  62867. this.volumetricLightFinalPostProcess.dispose(camera);
  62868. }
  62869. if (this.lensFlarePostProcess) {
  62870. this.lensFlarePostProcess.dispose(camera);
  62871. }
  62872. if (this.lensFlareComposePostProcess) {
  62873. this.lensFlareComposePostProcess.dispose(camera);
  62874. }
  62875. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  62876. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  62877. }
  62878. if (this.luminancePostProcess) {
  62879. this.luminancePostProcess.dispose(camera);
  62880. }
  62881. if (this.hdrPostProcess) {
  62882. this.hdrPostProcess.dispose(camera);
  62883. }
  62884. if (this.hdrFinalPostProcess) {
  62885. this.hdrFinalPostProcess.dispose(camera);
  62886. }
  62887. if (this.depthOfFieldPostProcess) {
  62888. this.depthOfFieldPostProcess.dispose(camera);
  62889. }
  62890. if (this.motionBlurPostProcess) {
  62891. this.motionBlurPostProcess.dispose(camera);
  62892. }
  62893. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  62894. this.blurHPostProcesses[j].dispose(camera);
  62895. }
  62896. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  62897. this.blurVPostProcesses[j].dispose(camera);
  62898. }
  62899. }
  62900. this.originalPostProcess = null;
  62901. this.downSampleX4PostProcess = null;
  62902. this.brightPassPostProcess = null;
  62903. this.textureAdderPostProcess = null;
  62904. this.textureAdderFinalPostProcess = null;
  62905. this.volumetricLightPostProcess = null;
  62906. this.volumetricLightSmoothXPostProcess = null;
  62907. this.volumetricLightSmoothYPostProcess = null;
  62908. this.volumetricLightMergePostProces = null;
  62909. this.volumetricLightFinalPostProcess = null;
  62910. this.lensFlarePostProcess = null;
  62911. this.lensFlareComposePostProcess = null;
  62912. this.luminancePostProcess = null;
  62913. this.hdrPostProcess = null;
  62914. this.hdrFinalPostProcess = null;
  62915. this.depthOfFieldPostProcess = null;
  62916. this.motionBlurPostProcess = null;
  62917. this.luminanceDownSamplePostProcesses = [];
  62918. this.blurHPostProcesses = [];
  62919. this.blurVPostProcesses = [];
  62920. };
  62921. // Dispose
  62922. StandardRenderingPipeline.prototype.dispose = function () {
  62923. this._disposePostProcesses();
  62924. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  62925. _super.prototype.dispose.call(this);
  62926. };
  62927. // Serialize rendering pipeline
  62928. StandardRenderingPipeline.prototype.serialize = function () {
  62929. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62930. serializationObject.customType = "StandardRenderingPipeline";
  62931. return serializationObject;
  62932. };
  62933. /**
  62934. * Static members
  62935. */
  62936. // Parse serialized pipeline
  62937. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  62938. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  62939. };
  62940. // Luminance steps
  62941. StandardRenderingPipeline.LuminanceSteps = 6;
  62942. __decorate([
  62943. BABYLON.serialize()
  62944. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  62945. __decorate([
  62946. BABYLON.serialize()
  62947. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  62948. __decorate([
  62949. BABYLON.serialize()
  62950. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  62951. __decorate([
  62952. BABYLON.serialize()
  62953. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  62954. __decorate([
  62955. BABYLON.serializeAsTexture("lensTexture")
  62956. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  62957. __decorate([
  62958. BABYLON.serialize()
  62959. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  62960. __decorate([
  62961. BABYLON.serialize()
  62962. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  62963. __decorate([
  62964. BABYLON.serialize()
  62965. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  62966. __decorate([
  62967. BABYLON.serialize()
  62968. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  62969. __decorate([
  62970. BABYLON.serialize()
  62971. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  62972. __decorate([
  62973. BABYLON.serialize()
  62974. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  62975. __decorate([
  62976. BABYLON.serializeAsTexture("lensColorTexture")
  62977. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  62978. __decorate([
  62979. BABYLON.serialize()
  62980. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  62981. __decorate([
  62982. BABYLON.serialize()
  62983. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  62984. __decorate([
  62985. BABYLON.serialize()
  62986. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  62987. __decorate([
  62988. BABYLON.serialize()
  62989. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  62990. __decorate([
  62991. BABYLON.serializeAsTexture("lensStarTexture")
  62992. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  62993. __decorate([
  62994. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  62995. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  62996. __decorate([
  62997. BABYLON.serialize()
  62998. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  62999. __decorate([
  63000. BABYLON.serialize()
  63001. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63002. __decorate([
  63003. BABYLON.serialize()
  63004. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63005. __decorate([
  63006. BABYLON.serialize()
  63007. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63008. __decorate([
  63009. BABYLON.serialize()
  63010. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63011. __decorate([
  63012. BABYLON.serialize()
  63013. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63014. __decorate([
  63015. BABYLON.serialize()
  63016. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63017. __decorate([
  63018. BABYLON.serialize()
  63019. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63020. __decorate([
  63021. BABYLON.serialize()
  63022. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63023. __decorate([
  63024. BABYLON.serialize()
  63025. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63026. __decorate([
  63027. BABYLON.serialize()
  63028. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63029. __decorate([
  63030. BABYLON.serialize()
  63031. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63032. return StandardRenderingPipeline;
  63033. }(BABYLON.PostProcessRenderPipeline));
  63034. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63035. })(BABYLON || (BABYLON = {}));
  63036. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63037. var BABYLON;
  63038. (function (BABYLON) {
  63039. var FxaaPostProcess = /** @class */ (function (_super) {
  63040. __extends(FxaaPostProcess, _super);
  63041. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63042. if (camera === void 0) { camera = null; }
  63043. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63044. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63045. _this.onApplyObservable.add(function (effect) {
  63046. var texelSize = _this.texelSize;
  63047. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63048. });
  63049. return _this;
  63050. }
  63051. return FxaaPostProcess;
  63052. }(BABYLON.PostProcess));
  63053. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63054. })(BABYLON || (BABYLON = {}));
  63055. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63056. var BABYLON;
  63057. (function (BABYLON) {
  63058. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63059. __extends(DefaultRenderingPipeline, _super);
  63060. /**
  63061. * @constructor
  63062. * @param {string} name - The rendering pipeline name
  63063. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63064. * @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)
  63065. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63066. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63067. */
  63068. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63069. if (automaticBuild === void 0) { automaticBuild = true; }
  63070. var _this = _super.call(this, scene.getEngine(), name) || this;
  63071. _this.PassPostProcessId = "PassPostProcessEffect";
  63072. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63073. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63074. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63075. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63076. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63077. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63078. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63079. // IAnimatable
  63080. _this.animations = [];
  63081. // Values
  63082. _this._bloomEnabled = false;
  63083. _this._fxaaEnabled = false;
  63084. _this._imageProcessingEnabled = true;
  63085. _this._bloomScale = 0.6;
  63086. _this._buildAllowed = true;
  63087. /**
  63088. * Specifies the size of the bloom blur kernel, relative to the final output size
  63089. */
  63090. _this.bloomKernel = 64;
  63091. /**
  63092. * Specifies the weight of the bloom in the final rendering
  63093. */
  63094. _this._bloomWeight = 0.15;
  63095. _this._cameras = cameras || [];
  63096. _this._buildAllowed = automaticBuild;
  63097. // Initialize
  63098. _this._scene = scene;
  63099. var caps = _this._scene.getEngine().getCaps();
  63100. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63101. // Misc
  63102. if (_this._hdr) {
  63103. if (caps.textureHalfFloatRender) {
  63104. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63105. }
  63106. else if (caps.textureFloatRender) {
  63107. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63108. }
  63109. }
  63110. else {
  63111. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63112. }
  63113. // Attach
  63114. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63115. _this._buildPipeline();
  63116. return _this;
  63117. }
  63118. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63119. get: function () {
  63120. return this._bloomWeight;
  63121. },
  63122. set: function (value) {
  63123. if (this._bloomWeight === value) {
  63124. return;
  63125. }
  63126. this._bloomWeight = value;
  63127. if (this._hdr && this.copyBack) {
  63128. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63129. }
  63130. },
  63131. enumerable: true,
  63132. configurable: true
  63133. });
  63134. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63135. get: function () {
  63136. return this._bloomScale;
  63137. },
  63138. set: function (value) {
  63139. if (this._bloomScale === value) {
  63140. return;
  63141. }
  63142. this._bloomScale = value;
  63143. this._buildPipeline();
  63144. },
  63145. enumerable: true,
  63146. configurable: true
  63147. });
  63148. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63149. get: function () {
  63150. return this._bloomEnabled;
  63151. },
  63152. set: function (enabled) {
  63153. if (this._bloomEnabled === enabled) {
  63154. return;
  63155. }
  63156. this._bloomEnabled = enabled;
  63157. this._buildPipeline();
  63158. },
  63159. enumerable: true,
  63160. configurable: true
  63161. });
  63162. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63163. get: function () {
  63164. return this._fxaaEnabled;
  63165. },
  63166. set: function (enabled) {
  63167. if (this._fxaaEnabled === enabled) {
  63168. return;
  63169. }
  63170. this._fxaaEnabled = enabled;
  63171. this._buildPipeline();
  63172. },
  63173. enumerable: true,
  63174. configurable: true
  63175. });
  63176. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63177. get: function () {
  63178. return this._imageProcessingEnabled;
  63179. },
  63180. set: function (enabled) {
  63181. if (this._imageProcessingEnabled === enabled) {
  63182. return;
  63183. }
  63184. this._imageProcessingEnabled = enabled;
  63185. this._buildPipeline();
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. /**
  63191. * Force the compilation of the entire pipeline.
  63192. */
  63193. DefaultRenderingPipeline.prototype.prepare = function () {
  63194. var previousState = this._buildAllowed;
  63195. this._buildAllowed = true;
  63196. this._buildPipeline();
  63197. this._buildAllowed = previousState;
  63198. };
  63199. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63200. var _this = this;
  63201. if (!this._buildAllowed) {
  63202. return;
  63203. }
  63204. var engine = this._scene.getEngine();
  63205. this._disposePostProcesses();
  63206. this._reset();
  63207. if (this.bloomEnabled) {
  63208. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63209. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63210. if (!this._hdr) {
  63211. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63212. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63213. this.highlights.autoClear = false;
  63214. this.highlights.alwaysForcePOT = true;
  63215. }
  63216. 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);
  63217. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63218. this.blurX.alwaysForcePOT = true;
  63219. this.blurX.autoClear = false;
  63220. this.blurX.onActivateObservable.add(function () {
  63221. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63222. _this.blurX.kernel = _this.bloomKernel * dw;
  63223. });
  63224. 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);
  63225. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63226. this.blurY.alwaysForcePOT = true;
  63227. this.blurY.autoClear = false;
  63228. this.blurY.onActivateObservable.add(function () {
  63229. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63230. _this.blurY.kernel = _this.bloomKernel * dh;
  63231. });
  63232. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63233. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  63234. this.copyBack.alwaysForcePOT = true;
  63235. if (this._hdr) {
  63236. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  63237. var w = this.bloomWeight;
  63238. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  63239. }
  63240. else {
  63241. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  63242. }
  63243. this.copyBack.autoClear = false;
  63244. }
  63245. if (this._imageProcessingEnabled) {
  63246. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63247. if (this._hdr) {
  63248. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  63249. }
  63250. else {
  63251. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  63252. }
  63253. }
  63254. if (this.fxaaEnabled) {
  63255. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63256. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  63257. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63258. }
  63259. else if (this._hdr && this.imageProcessing) {
  63260. this.finalMerge = this.imageProcessing;
  63261. }
  63262. else {
  63263. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63264. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  63265. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63266. }
  63267. if (this.bloomEnabled) {
  63268. if (this._hdr) {
  63269. this.copyBack.shareOutputWith(this.blurX);
  63270. if (this.imageProcessing) {
  63271. this.imageProcessing.shareOutputWith(this.pass);
  63272. this.imageProcessing.autoClear = false;
  63273. }
  63274. else if (this.fxaa) {
  63275. this.fxaa.shareOutputWith(this.pass);
  63276. }
  63277. else {
  63278. this.finalMerge.shareOutputWith(this.pass);
  63279. }
  63280. }
  63281. else {
  63282. if (this.fxaa) {
  63283. this.fxaa.shareOutputWith(this.pass);
  63284. }
  63285. else {
  63286. this.finalMerge.shareOutputWith(this.pass);
  63287. }
  63288. }
  63289. }
  63290. if (this._cameras !== null) {
  63291. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63292. }
  63293. };
  63294. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  63295. for (var i = 0; i < this._cameras.length; i++) {
  63296. var camera = this._cameras[i];
  63297. if (this.pass) {
  63298. this.pass.dispose(camera);
  63299. }
  63300. if (this.highlights) {
  63301. this.highlights.dispose(camera);
  63302. }
  63303. if (this.blurX) {
  63304. this.blurX.dispose(camera);
  63305. }
  63306. if (this.blurY) {
  63307. this.blurY.dispose(camera);
  63308. }
  63309. if (this.copyBack) {
  63310. this.copyBack.dispose(camera);
  63311. }
  63312. if (this.imageProcessing) {
  63313. this.imageProcessing.dispose(camera);
  63314. }
  63315. if (this.fxaa) {
  63316. this.fxaa.dispose(camera);
  63317. }
  63318. if (this.finalMerge) {
  63319. this.finalMerge.dispose(camera);
  63320. }
  63321. }
  63322. this.pass = null;
  63323. this.highlights = null;
  63324. this.blurX = null;
  63325. this.blurY = null;
  63326. this.copyBack = null;
  63327. this.imageProcessing = null;
  63328. this.fxaa = null;
  63329. this.finalMerge = null;
  63330. };
  63331. // Dispose
  63332. DefaultRenderingPipeline.prototype.dispose = function () {
  63333. this._disposePostProcesses();
  63334. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63335. _super.prototype.dispose.call(this);
  63336. };
  63337. // Serialize rendering pipeline
  63338. DefaultRenderingPipeline.prototype.serialize = function () {
  63339. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63340. serializationObject.customType = "DefaultRenderingPipeline";
  63341. return serializationObject;
  63342. };
  63343. // Parse serialized pipeline
  63344. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63345. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  63346. };
  63347. __decorate([
  63348. BABYLON.serialize()
  63349. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  63350. __decorate([
  63351. BABYLON.serialize()
  63352. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  63353. __decorate([
  63354. BABYLON.serialize()
  63355. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  63356. __decorate([
  63357. BABYLON.serialize()
  63358. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  63359. __decorate([
  63360. BABYLON.serialize()
  63361. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  63362. __decorate([
  63363. BABYLON.serialize()
  63364. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  63365. __decorate([
  63366. BABYLON.serialize()
  63367. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  63368. __decorate([
  63369. BABYLON.serialize()
  63370. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  63371. return DefaultRenderingPipeline;
  63372. }(BABYLON.PostProcessRenderPipeline));
  63373. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  63374. })(BABYLON || (BABYLON = {}));
  63375. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  63376. var BABYLON;
  63377. (function (BABYLON) {
  63378. /**
  63379. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  63380. */
  63381. var GeometryBufferRenderer = /** @class */ (function () {
  63382. /**
  63383. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  63384. * @param scene The scene the buffer belongs to
  63385. * @param ratio How big is the buffer related to the main canvas.
  63386. */
  63387. function GeometryBufferRenderer(scene, ratio) {
  63388. if (ratio === void 0) { ratio = 1; }
  63389. this._enablePosition = false;
  63390. this._scene = scene;
  63391. this._ratio = ratio;
  63392. // Render target
  63393. this._createRenderTargets();
  63394. }
  63395. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  63396. /**
  63397. * Set the render list (meshes to be rendered) used in the G buffer.
  63398. */
  63399. set: function (meshes) {
  63400. this._multiRenderTarget.renderList = meshes;
  63401. },
  63402. enumerable: true,
  63403. configurable: true
  63404. });
  63405. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  63406. /**
  63407. * Gets wether or not G buffer are supported by the running hardware.
  63408. * This requires draw buffer supports
  63409. */
  63410. get: function () {
  63411. return this._multiRenderTarget.isSupported;
  63412. },
  63413. enumerable: true,
  63414. configurable: true
  63415. });
  63416. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  63417. /**
  63418. * Gets wether or not position are enabled for the G buffer.
  63419. */
  63420. get: function () {
  63421. return this._enablePosition;
  63422. },
  63423. /**
  63424. * Sets wether or not position are enabled for the G buffer.
  63425. */
  63426. set: function (enable) {
  63427. this._enablePosition = enable;
  63428. this.dispose();
  63429. this._createRenderTargets();
  63430. },
  63431. enumerable: true,
  63432. configurable: true
  63433. });
  63434. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  63435. /**
  63436. * Gets the scene associated with the buffer.
  63437. */
  63438. get: function () {
  63439. return this._scene;
  63440. },
  63441. enumerable: true,
  63442. configurable: true
  63443. });
  63444. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  63445. /**
  63446. * Gets the ratio used by the buffer during its creation.
  63447. * How big is the buffer related to the main canvas.
  63448. */
  63449. get: function () {
  63450. return this._ratio;
  63451. },
  63452. enumerable: true,
  63453. configurable: true
  63454. });
  63455. /**
  63456. * Checks wether everything is ready to render a submesh to the G buffer.
  63457. * @param subMesh the submesh to check readiness for
  63458. * @param useInstances is the mesh drawn using instance or not
  63459. * @returns true if ready otherwise false
  63460. */
  63461. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  63462. var material = subMesh.getMaterial();
  63463. if (material && material.disableDepthWrite) {
  63464. return false;
  63465. }
  63466. var defines = [];
  63467. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63468. var mesh = subMesh.getMesh();
  63469. // Alpha test
  63470. if (material && material.needAlphaTesting()) {
  63471. defines.push("#define ALPHATEST");
  63472. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63473. attribs.push(BABYLON.VertexBuffer.UVKind);
  63474. defines.push("#define UV1");
  63475. }
  63476. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63477. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63478. defines.push("#define UV2");
  63479. }
  63480. }
  63481. // Buffers
  63482. if (this._enablePosition) {
  63483. defines.push("#define POSITION");
  63484. }
  63485. // Bones
  63486. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63487. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63488. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63489. if (mesh.numBoneInfluencers > 4) {
  63490. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63491. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63492. }
  63493. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63494. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  63495. }
  63496. else {
  63497. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63498. }
  63499. // Instances
  63500. if (useInstances) {
  63501. defines.push("#define INSTANCES");
  63502. attribs.push("world0");
  63503. attribs.push("world1");
  63504. attribs.push("world2");
  63505. attribs.push("world3");
  63506. }
  63507. // Get correct effect
  63508. var join = defines.join("\n");
  63509. if (this._cachedDefines !== join) {
  63510. this._cachedDefines = join;
  63511. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  63512. }
  63513. return this._effect.isReady();
  63514. };
  63515. /**
  63516. * Gets the current underlying G Buffer.
  63517. * @returns the buffer
  63518. */
  63519. GeometryBufferRenderer.prototype.getGBuffer = function () {
  63520. return this._multiRenderTarget;
  63521. };
  63522. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  63523. /**
  63524. * Gets the number of samples used to render the buffer (anti aliasing).
  63525. */
  63526. get: function () {
  63527. return this._multiRenderTarget.samples;
  63528. },
  63529. /**
  63530. * Sets the number of samples used to render the buffer (anti aliasing).
  63531. */
  63532. set: function (value) {
  63533. this._multiRenderTarget.samples = value;
  63534. },
  63535. enumerable: true,
  63536. configurable: true
  63537. });
  63538. /**
  63539. * Disposes the renderer and frees up associated resources.
  63540. */
  63541. GeometryBufferRenderer.prototype.dispose = function () {
  63542. this.getGBuffer().dispose();
  63543. };
  63544. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  63545. var _this = this;
  63546. var engine = this._scene.getEngine();
  63547. var count = this._enablePosition ? 3 : 2;
  63548. 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 });
  63549. if (!this.isSupported) {
  63550. return;
  63551. }
  63552. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63553. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63554. this._multiRenderTarget.refreshRate = 1;
  63555. this._multiRenderTarget.renderParticles = false;
  63556. this._multiRenderTarget.renderList = null;
  63557. // set default depth value to 1.0 (far away)
  63558. this._multiRenderTarget.onClearObservable.add(function (engine) {
  63559. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  63560. });
  63561. // Custom render function
  63562. var renderSubMesh = function (subMesh) {
  63563. var mesh = subMesh.getRenderingMesh();
  63564. var scene = _this._scene;
  63565. var engine = scene.getEngine();
  63566. var material = subMesh.getMaterial();
  63567. if (!material) {
  63568. return;
  63569. }
  63570. // Culling
  63571. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  63572. // Managing instances
  63573. var batch = mesh._getInstancesRenderList(subMesh._id);
  63574. if (batch.mustReturn) {
  63575. return;
  63576. }
  63577. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  63578. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  63579. engine.enableEffect(_this._effect);
  63580. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  63581. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  63582. _this._effect.setMatrix("view", scene.getViewMatrix());
  63583. // Alpha test
  63584. if (material && material.needAlphaTesting()) {
  63585. var alphaTexture = material.getAlphaTestTexture();
  63586. if (alphaTexture) {
  63587. _this._effect.setTexture("diffuseSampler", alphaTexture);
  63588. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63589. }
  63590. }
  63591. // Bones
  63592. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63593. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63594. }
  63595. // Draw
  63596. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  63597. }
  63598. };
  63599. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63600. var index;
  63601. if (depthOnlySubMeshes.length) {
  63602. engine.setColorWrite(false);
  63603. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63604. renderSubMesh(depthOnlySubMeshes.data[index]);
  63605. }
  63606. engine.setColorWrite(true);
  63607. }
  63608. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63609. renderSubMesh(opaqueSubMeshes.data[index]);
  63610. }
  63611. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63612. renderSubMesh(alphaTestSubMeshes.data[index]);
  63613. }
  63614. };
  63615. };
  63616. return GeometryBufferRenderer;
  63617. }());
  63618. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  63619. })(BABYLON || (BABYLON = {}));
  63620. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  63621. var BABYLON;
  63622. (function (BABYLON) {
  63623. var RefractionPostProcess = /** @class */ (function (_super) {
  63624. __extends(RefractionPostProcess, _super);
  63625. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  63626. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  63627. _this.color = color;
  63628. _this.depth = depth;
  63629. _this.colorLevel = colorLevel;
  63630. _this.onActivateObservable.add(function (cam) {
  63631. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  63632. });
  63633. _this.onApplyObservable.add(function (effect) {
  63634. effect.setColor3("baseColor", _this.color);
  63635. effect.setFloat("depth", _this.depth);
  63636. effect.setFloat("colorLevel", _this.colorLevel);
  63637. effect.setTexture("refractionSampler", _this._refRexture);
  63638. });
  63639. return _this;
  63640. }
  63641. // Methods
  63642. RefractionPostProcess.prototype.dispose = function (camera) {
  63643. if (this._refRexture) {
  63644. this._refRexture.dispose();
  63645. }
  63646. _super.prototype.dispose.call(this, camera);
  63647. };
  63648. return RefractionPostProcess;
  63649. }(BABYLON.PostProcess));
  63650. BABYLON.RefractionPostProcess = RefractionPostProcess;
  63651. })(BABYLON || (BABYLON = {}));
  63652. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  63653. var BABYLON;
  63654. (function (BABYLON) {
  63655. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  63656. __extends(BlackAndWhitePostProcess, _super);
  63657. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  63658. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  63659. _this.degree = 1;
  63660. _this.onApplyObservable.add(function (effect) {
  63661. effect.setFloat("degree", _this.degree);
  63662. });
  63663. return _this;
  63664. }
  63665. return BlackAndWhitePostProcess;
  63666. }(BABYLON.PostProcess));
  63667. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  63668. })(BABYLON || (BABYLON = {}));
  63669. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  63670. var BABYLON;
  63671. (function (BABYLON) {
  63672. var ConvolutionPostProcess = /** @class */ (function (_super) {
  63673. __extends(ConvolutionPostProcess, _super);
  63674. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  63675. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  63676. _this.kernel = kernel;
  63677. _this.onApply = function (effect) {
  63678. effect.setFloat2("screenSize", _this.width, _this.height);
  63679. effect.setArray("kernel", _this.kernel);
  63680. };
  63681. return _this;
  63682. }
  63683. // Statics
  63684. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  63685. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  63686. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  63687. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  63688. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  63689. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  63690. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  63691. return ConvolutionPostProcess;
  63692. }(BABYLON.PostProcess));
  63693. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  63694. })(BABYLON || (BABYLON = {}));
  63695. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  63696. var BABYLON;
  63697. (function (BABYLON) {
  63698. var FilterPostProcess = /** @class */ (function (_super) {
  63699. __extends(FilterPostProcess, _super);
  63700. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  63701. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  63702. _this.kernelMatrix = kernelMatrix;
  63703. _this.onApply = function (effect) {
  63704. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  63705. };
  63706. return _this;
  63707. }
  63708. return FilterPostProcess;
  63709. }(BABYLON.PostProcess));
  63710. BABYLON.FilterPostProcess = FilterPostProcess;
  63711. })(BABYLON || (BABYLON = {}));
  63712. //# sourceMappingURL=babylon.filterPostProcess.js.map
  63713. var BABYLON;
  63714. (function (BABYLON) {
  63715. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  63716. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  63717. __extends(VolumetricLightScatteringPostProcess, _super);
  63718. /**
  63719. * @constructor
  63720. * @param {string} name - The post-process name
  63721. * @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)
  63722. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  63723. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  63724. * @param {number} samples - The post-process quality, default 100
  63725. * @param {number} samplingMode - The post-process filtering mode
  63726. * @param {BABYLON.Engine} engine - The babylon engine
  63727. * @param {boolean} reusable - If the post-process is reusable
  63728. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  63729. */
  63730. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  63731. if (samples === void 0) { samples = 100; }
  63732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63733. 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;
  63734. _this._screenCoordinates = BABYLON.Vector2.Zero();
  63735. /**
  63736. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  63737. * @type {Vector3}
  63738. */
  63739. _this.customMeshPosition = BABYLON.Vector3.Zero();
  63740. /**
  63741. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  63742. * @type {boolean}
  63743. */
  63744. _this.useCustomMeshPosition = false;
  63745. /**
  63746. * If the post-process should inverse the light scattering direction
  63747. * @type {boolean}
  63748. */
  63749. _this.invert = true;
  63750. /**
  63751. * Array containing the excluded meshes not rendered in the internal pass
  63752. */
  63753. _this.excludedMeshes = new Array();
  63754. /**
  63755. * Controls the overall intensity of the post-process
  63756. * @type {number}
  63757. */
  63758. _this.exposure = 0.3;
  63759. /**
  63760. * Dissipates each sample's contribution in range [0, 1]
  63761. * @type {number}
  63762. */
  63763. _this.decay = 0.96815;
  63764. /**
  63765. * Controls the overall intensity of each sample
  63766. * @type {number}
  63767. */
  63768. _this.weight = 0.58767;
  63769. /**
  63770. * Controls the density of each sample
  63771. * @type {number}
  63772. */
  63773. _this.density = 0.926;
  63774. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  63775. engine = scene.getEngine();
  63776. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  63777. // Configure mesh
  63778. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  63779. // Configure
  63780. _this._createPass(scene, ratio.passRatio || ratio);
  63781. _this.onActivate = function (camera) {
  63782. if (!_this.isSupported) {
  63783. _this.dispose(camera);
  63784. }
  63785. _this.onActivate = null;
  63786. };
  63787. _this.onApplyObservable.add(function (effect) {
  63788. _this._updateMeshScreenCoordinates(scene);
  63789. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  63790. effect.setFloat("exposure", _this.exposure);
  63791. effect.setFloat("decay", _this.decay);
  63792. effect.setFloat("weight", _this.weight);
  63793. effect.setFloat("density", _this.density);
  63794. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  63795. });
  63796. return _this;
  63797. }
  63798. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  63799. get: function () {
  63800. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63801. return false;
  63802. },
  63803. set: function (useDiffuseColor) {
  63804. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  63805. },
  63806. enumerable: true,
  63807. configurable: true
  63808. });
  63809. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  63810. return "VolumetricLightScatteringPostProcess";
  63811. };
  63812. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  63813. var mesh = subMesh.getMesh();
  63814. // Render this.mesh as default
  63815. if (mesh === this.mesh && mesh.material) {
  63816. return mesh.material.isReady(mesh);
  63817. }
  63818. var defines = [];
  63819. var attribs = [BABYLON.VertexBuffer.PositionKind];
  63820. var material = subMesh.getMaterial();
  63821. // Alpha test
  63822. if (material) {
  63823. if (material.needAlphaTesting()) {
  63824. defines.push("#define ALPHATEST");
  63825. }
  63826. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63827. attribs.push(BABYLON.VertexBuffer.UVKind);
  63828. defines.push("#define UV1");
  63829. }
  63830. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63831. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63832. defines.push("#define UV2");
  63833. }
  63834. }
  63835. // Bones
  63836. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63837. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63838. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63839. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63840. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  63841. }
  63842. else {
  63843. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63844. }
  63845. // Instances
  63846. if (useInstances) {
  63847. defines.push("#define INSTANCES");
  63848. attribs.push("world0");
  63849. attribs.push("world1");
  63850. attribs.push("world2");
  63851. attribs.push("world3");
  63852. }
  63853. // Get correct effect
  63854. var join = defines.join("\n");
  63855. if (this._cachedDefines !== join) {
  63856. this._cachedDefines = join;
  63857. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  63858. }
  63859. return this._volumetricLightScatteringPass.isReady();
  63860. };
  63861. /**
  63862. * Sets the new light position for light scattering effect
  63863. * @param {BABYLON.Vector3} The new custom light position
  63864. */
  63865. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  63866. this.customMeshPosition = position;
  63867. };
  63868. /**
  63869. * Returns the light position for light scattering effect
  63870. * @return {BABYLON.Vector3} The custom light position
  63871. */
  63872. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  63873. return this.customMeshPosition;
  63874. };
  63875. /**
  63876. * Disposes the internal assets and detaches the post-process from the camera
  63877. */
  63878. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  63879. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  63880. if (rttIndex !== -1) {
  63881. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  63882. }
  63883. this._volumetricLightScatteringRTT.dispose();
  63884. _super.prototype.dispose.call(this, camera);
  63885. };
  63886. /**
  63887. * Returns the render target texture used by the post-process
  63888. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  63889. */
  63890. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  63891. return this._volumetricLightScatteringRTT;
  63892. };
  63893. // Private methods
  63894. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  63895. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  63896. return true;
  63897. }
  63898. return false;
  63899. };
  63900. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  63901. var _this = this;
  63902. var engine = scene.getEngine();
  63903. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63904. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63905. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63906. this._volumetricLightScatteringRTT.renderList = null;
  63907. this._volumetricLightScatteringRTT.renderParticles = false;
  63908. var camera = this.getCamera();
  63909. if (camera) {
  63910. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  63911. }
  63912. else {
  63913. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  63914. }
  63915. // Custom render function for submeshes
  63916. var renderSubMesh = function (subMesh) {
  63917. var mesh = subMesh.getRenderingMesh();
  63918. if (_this._meshExcluded(mesh)) {
  63919. return;
  63920. }
  63921. var material = subMesh.getMaterial();
  63922. if (!material) {
  63923. return;
  63924. }
  63925. var scene = mesh.getScene();
  63926. var engine = scene.getEngine();
  63927. // Culling
  63928. engine.setState(material.backFaceCulling);
  63929. // Managing instances
  63930. var batch = mesh._getInstancesRenderList(subMesh._id);
  63931. if (batch.mustReturn) {
  63932. return;
  63933. }
  63934. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  63935. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  63936. var effect = _this._volumetricLightScatteringPass;
  63937. if (mesh === _this.mesh) {
  63938. if (subMesh.effect) {
  63939. effect = subMesh.effect;
  63940. }
  63941. else {
  63942. effect = material.getEffect();
  63943. }
  63944. }
  63945. engine.enableEffect(effect);
  63946. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  63947. if (mesh === _this.mesh) {
  63948. material.bind(mesh.getWorldMatrix(), mesh);
  63949. }
  63950. else {
  63951. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  63952. // Alpha test
  63953. if (material && material.needAlphaTesting()) {
  63954. var alphaTexture = material.getAlphaTestTexture();
  63955. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  63956. if (alphaTexture) {
  63957. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  63958. }
  63959. }
  63960. // Bones
  63961. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  63962. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  63963. }
  63964. }
  63965. // Draw
  63966. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  63967. }
  63968. };
  63969. // Render target texture callbacks
  63970. var savedSceneClearColor;
  63971. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  63972. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  63973. savedSceneClearColor = scene.clearColor;
  63974. scene.clearColor = sceneClearColor;
  63975. });
  63976. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  63977. scene.clearColor = savedSceneClearColor;
  63978. });
  63979. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  63980. var engine = scene.getEngine();
  63981. var index;
  63982. if (depthOnlySubMeshes.length) {
  63983. engine.setColorWrite(false);
  63984. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  63985. renderSubMesh(depthOnlySubMeshes.data[index]);
  63986. }
  63987. engine.setColorWrite(true);
  63988. }
  63989. for (index = 0; index < opaqueSubMeshes.length; index++) {
  63990. renderSubMesh(opaqueSubMeshes.data[index]);
  63991. }
  63992. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  63993. renderSubMesh(alphaTestSubMeshes.data[index]);
  63994. }
  63995. if (transparentSubMeshes.length) {
  63996. // Sort sub meshes
  63997. for (index = 0; index < transparentSubMeshes.length; index++) {
  63998. var submesh = transparentSubMeshes.data[index];
  63999. var boundingInfo = submesh.getBoundingInfo();
  64000. if (boundingInfo && scene.activeCamera) {
  64001. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64002. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64003. }
  64004. }
  64005. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64006. sortedArray.sort(function (a, b) {
  64007. // Alpha index first
  64008. if (a._alphaIndex > b._alphaIndex) {
  64009. return 1;
  64010. }
  64011. if (a._alphaIndex < b._alphaIndex) {
  64012. return -1;
  64013. }
  64014. // Then distance to camera
  64015. if (a._distanceToCamera < b._distanceToCamera) {
  64016. return 1;
  64017. }
  64018. if (a._distanceToCamera > b._distanceToCamera) {
  64019. return -1;
  64020. }
  64021. return 0;
  64022. });
  64023. // Render sub meshes
  64024. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64025. for (index = 0; index < sortedArray.length; index++) {
  64026. renderSubMesh(sortedArray[index]);
  64027. }
  64028. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64029. }
  64030. };
  64031. };
  64032. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64033. var transform = scene.getTransformMatrix();
  64034. var meshPosition;
  64035. if (this.useCustomMeshPosition) {
  64036. meshPosition = this.customMeshPosition;
  64037. }
  64038. else if (this.attachedNode) {
  64039. meshPosition = this.attachedNode.position;
  64040. }
  64041. else {
  64042. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64043. }
  64044. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64045. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64046. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64047. if (this.invert)
  64048. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64049. };
  64050. // Static methods
  64051. /**
  64052. * Creates a default mesh for the Volumeric Light Scattering post-process
  64053. * @param {string} The mesh name
  64054. * @param {BABYLON.Scene} The scene where to create the mesh
  64055. * @return {BABYLON.Mesh} the default mesh
  64056. */
  64057. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64058. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64059. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64060. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64061. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64062. mesh.material = material;
  64063. return mesh;
  64064. };
  64065. __decorate([
  64066. BABYLON.serializeAsVector3()
  64067. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64068. __decorate([
  64069. BABYLON.serialize()
  64070. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64071. __decorate([
  64072. BABYLON.serialize()
  64073. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64074. __decorate([
  64075. BABYLON.serializeAsMeshReference()
  64076. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64077. __decorate([
  64078. BABYLON.serialize()
  64079. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64080. __decorate([
  64081. BABYLON.serialize()
  64082. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64083. __decorate([
  64084. BABYLON.serialize()
  64085. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64086. __decorate([
  64087. BABYLON.serialize()
  64088. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64089. __decorate([
  64090. BABYLON.serialize()
  64091. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64092. return VolumetricLightScatteringPostProcess;
  64093. }(BABYLON.PostProcess));
  64094. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64095. })(BABYLON || (BABYLON = {}));
  64096. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64097. //
  64098. // This post-process allows the modification of rendered colors by using
  64099. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64100. //
  64101. // The object needs to be provided an url to a texture containing the color
  64102. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64103. // Use an image editing software to tweak the LUT to match your needs.
  64104. //
  64105. // For an example of a color LUT, see here:
  64106. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64107. // For explanations on color grading, see here:
  64108. // http://udn.epicgames.com/Three/ColorGrading.html
  64109. //
  64110. var BABYLON;
  64111. (function (BABYLON) {
  64112. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64113. __extends(ColorCorrectionPostProcess, _super);
  64114. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64115. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64116. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64117. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64118. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64119. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64120. _this.onApply = function (effect) {
  64121. effect.setTexture("colorTable", _this._colorTableTexture);
  64122. };
  64123. return _this;
  64124. }
  64125. return ColorCorrectionPostProcess;
  64126. }(BABYLON.PostProcess));
  64127. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64128. })(BABYLON || (BABYLON = {}));
  64129. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64130. var BABYLON;
  64131. (function (BABYLON) {
  64132. var TonemappingOperator;
  64133. (function (TonemappingOperator) {
  64134. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64135. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64136. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64137. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64138. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64139. ;
  64140. var TonemapPostProcess = /** @class */ (function (_super) {
  64141. __extends(TonemapPostProcess, _super);
  64142. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64144. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64145. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64146. _this._operator = _operator;
  64147. _this.exposureAdjustment = exposureAdjustment;
  64148. var defines = "#define ";
  64149. if (_this._operator === TonemappingOperator.Hable)
  64150. defines += "HABLE_TONEMAPPING";
  64151. else if (_this._operator === TonemappingOperator.Reinhard)
  64152. defines += "REINHARD_TONEMAPPING";
  64153. else if (_this._operator === TonemappingOperator.HejiDawson)
  64154. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64155. else if (_this._operator === TonemappingOperator.Photographic)
  64156. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64157. //sadly a second call to create the effect.
  64158. _this.updateEffect(defines);
  64159. _this.onApply = function (effect) {
  64160. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64161. };
  64162. return _this;
  64163. }
  64164. return TonemapPostProcess;
  64165. }(BABYLON.PostProcess));
  64166. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64167. })(BABYLON || (BABYLON = {}));
  64168. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64169. var BABYLON;
  64170. (function (BABYLON) {
  64171. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64172. __extends(DisplayPassPostProcess, _super);
  64173. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64174. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64175. }
  64176. return DisplayPassPostProcess;
  64177. }(BABYLON.PostProcess));
  64178. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64179. })(BABYLON || (BABYLON = {}));
  64180. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64181. var BABYLON;
  64182. (function (BABYLON) {
  64183. var HighlightsPostProcess = /** @class */ (function (_super) {
  64184. __extends(HighlightsPostProcess, _super);
  64185. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64186. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64187. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64188. }
  64189. return HighlightsPostProcess;
  64190. }(BABYLON.PostProcess));
  64191. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64192. })(BABYLON || (BABYLON = {}));
  64193. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64194. var BABYLON;
  64195. (function (BABYLON) {
  64196. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64197. __extends(ImageProcessingPostProcess, _super);
  64198. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64199. if (camera === void 0) { camera = null; }
  64200. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64201. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64202. _this._fromLinearSpace = true;
  64203. /**
  64204. * Defines cache preventing GC.
  64205. */
  64206. _this._defines = {
  64207. IMAGEPROCESSING: false,
  64208. VIGNETTE: false,
  64209. VIGNETTEBLENDMODEMULTIPLY: false,
  64210. VIGNETTEBLENDMODEOPAQUE: false,
  64211. TONEMAPPING: false,
  64212. CONTRAST: false,
  64213. COLORCURVES: false,
  64214. COLORGRADING: false,
  64215. COLORGRADING3D: false,
  64216. FROMLINEARSPACE: false,
  64217. SAMPLER3DGREENDEPTH: false,
  64218. SAMPLER3DBGRMAP: false,
  64219. IMAGEPROCESSINGPOSTPROCESS: false,
  64220. EXPOSURE: false,
  64221. };
  64222. // Setup the configuration as forced by the constructor. This would then not force the
  64223. // scene materials output in linear space and let untouched the default forward pass.
  64224. if (imageProcessingConfiguration) {
  64225. imageProcessingConfiguration.applyByPostProcess = true;
  64226. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64227. // This will cause the shader to be compiled
  64228. _this.fromLinearSpace = false;
  64229. }
  64230. else {
  64231. _this._attachImageProcessingConfiguration(null, true);
  64232. _this.imageProcessingConfiguration.applyByPostProcess = true;
  64233. }
  64234. _this.onApply = function (effect) {
  64235. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  64236. };
  64237. return _this;
  64238. }
  64239. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  64240. /**
  64241. * Gets the image processing configuration used either in this material.
  64242. */
  64243. get: function () {
  64244. return this._imageProcessingConfiguration;
  64245. },
  64246. /**
  64247. * Sets the Default image processing configuration used either in the this material.
  64248. *
  64249. * If sets to null, the scene one is in use.
  64250. */
  64251. set: function (value) {
  64252. this._attachImageProcessingConfiguration(value);
  64253. },
  64254. enumerable: true,
  64255. configurable: true
  64256. });
  64257. /**
  64258. * Attaches a new image processing configuration to the PBR Material.
  64259. * @param configuration
  64260. */
  64261. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  64262. var _this = this;
  64263. if (doNotBuild === void 0) { doNotBuild = false; }
  64264. if (configuration === this._imageProcessingConfiguration) {
  64265. return;
  64266. }
  64267. // Detaches observer.
  64268. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64269. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64270. }
  64271. // Pick the scene configuration if needed.
  64272. if (!configuration) {
  64273. var scene = null;
  64274. var engine = this.getEngine();
  64275. var camera = this.getCamera();
  64276. if (camera) {
  64277. scene = camera.getScene();
  64278. }
  64279. else if (engine && engine.scenes) {
  64280. var scenes = engine.scenes;
  64281. scene = scenes[scenes.length - 1];
  64282. }
  64283. else {
  64284. scene = BABYLON.Engine.LastCreatedScene;
  64285. }
  64286. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  64287. }
  64288. else {
  64289. this._imageProcessingConfiguration = configuration;
  64290. }
  64291. // Attaches observer.
  64292. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  64293. _this._updateParameters();
  64294. });
  64295. // Ensure the effect will be rebuilt.
  64296. if (!doNotBuild) {
  64297. this._updateParameters();
  64298. }
  64299. };
  64300. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  64301. /**
  64302. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64303. */
  64304. get: function () {
  64305. return this.imageProcessingConfiguration.colorCurves;
  64306. },
  64307. /**
  64308. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64309. */
  64310. set: function (value) {
  64311. this.imageProcessingConfiguration.colorCurves = value;
  64312. },
  64313. enumerable: true,
  64314. configurable: true
  64315. });
  64316. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  64317. /**
  64318. * Gets wether the color curves effect is enabled.
  64319. */
  64320. get: function () {
  64321. return this.imageProcessingConfiguration.colorCurvesEnabled;
  64322. },
  64323. /**
  64324. * Sets wether the color curves effect is enabled.
  64325. */
  64326. set: function (value) {
  64327. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  64328. },
  64329. enumerable: true,
  64330. configurable: true
  64331. });
  64332. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  64333. /**
  64334. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64335. */
  64336. get: function () {
  64337. return this.imageProcessingConfiguration.colorGradingTexture;
  64338. },
  64339. /**
  64340. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64341. */
  64342. set: function (value) {
  64343. this.imageProcessingConfiguration.colorGradingTexture = value;
  64344. },
  64345. enumerable: true,
  64346. configurable: true
  64347. });
  64348. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  64349. /**
  64350. * Gets wether the color grading effect is enabled.
  64351. */
  64352. get: function () {
  64353. return this.imageProcessingConfiguration.colorGradingEnabled;
  64354. },
  64355. /**
  64356. * Gets wether the color grading effect is enabled.
  64357. */
  64358. set: function (value) {
  64359. this.imageProcessingConfiguration.colorGradingEnabled = value;
  64360. },
  64361. enumerable: true,
  64362. configurable: true
  64363. });
  64364. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  64365. /**
  64366. * Gets exposure used in the effect.
  64367. */
  64368. get: function () {
  64369. return this.imageProcessingConfiguration.exposure;
  64370. },
  64371. /**
  64372. * Sets exposure used in the effect.
  64373. */
  64374. set: function (value) {
  64375. this.imageProcessingConfiguration.exposure = value;
  64376. },
  64377. enumerable: true,
  64378. configurable: true
  64379. });
  64380. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  64381. /**
  64382. * Gets wether tonemapping is enabled or not.
  64383. */
  64384. get: function () {
  64385. return this._imageProcessingConfiguration.toneMappingEnabled;
  64386. },
  64387. /**
  64388. * Sets wether tonemapping is enabled or not
  64389. */
  64390. set: function (value) {
  64391. this._imageProcessingConfiguration.toneMappingEnabled = value;
  64392. },
  64393. enumerable: true,
  64394. configurable: true
  64395. });
  64396. ;
  64397. ;
  64398. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  64399. /**
  64400. * Gets contrast used in the effect.
  64401. */
  64402. get: function () {
  64403. return this.imageProcessingConfiguration.contrast;
  64404. },
  64405. /**
  64406. * Sets contrast used in the effect.
  64407. */
  64408. set: function (value) {
  64409. this.imageProcessingConfiguration.contrast = value;
  64410. },
  64411. enumerable: true,
  64412. configurable: true
  64413. });
  64414. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  64415. /**
  64416. * Gets Vignette stretch size.
  64417. */
  64418. get: function () {
  64419. return this.imageProcessingConfiguration.vignetteStretch;
  64420. },
  64421. /**
  64422. * Sets Vignette stretch size.
  64423. */
  64424. set: function (value) {
  64425. this.imageProcessingConfiguration.vignetteStretch = value;
  64426. },
  64427. enumerable: true,
  64428. configurable: true
  64429. });
  64430. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  64431. /**
  64432. * Gets Vignette centre X Offset.
  64433. */
  64434. get: function () {
  64435. return this.imageProcessingConfiguration.vignetteCentreX;
  64436. },
  64437. /**
  64438. * Sets Vignette centre X Offset.
  64439. */
  64440. set: function (value) {
  64441. this.imageProcessingConfiguration.vignetteCentreX = value;
  64442. },
  64443. enumerable: true,
  64444. configurable: true
  64445. });
  64446. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  64447. /**
  64448. * Gets Vignette centre Y Offset.
  64449. */
  64450. get: function () {
  64451. return this.imageProcessingConfiguration.vignetteCentreY;
  64452. },
  64453. /**
  64454. * Sets Vignette centre Y Offset.
  64455. */
  64456. set: function (value) {
  64457. this.imageProcessingConfiguration.vignetteCentreY = value;
  64458. },
  64459. enumerable: true,
  64460. configurable: true
  64461. });
  64462. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  64463. /**
  64464. * Gets Vignette weight or intensity of the vignette effect.
  64465. */
  64466. get: function () {
  64467. return this.imageProcessingConfiguration.vignetteWeight;
  64468. },
  64469. /**
  64470. * Sets Vignette weight or intensity of the vignette effect.
  64471. */
  64472. set: function (value) {
  64473. this.imageProcessingConfiguration.vignetteWeight = value;
  64474. },
  64475. enumerable: true,
  64476. configurable: true
  64477. });
  64478. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  64479. /**
  64480. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64481. * if vignetteEnabled is set to true.
  64482. */
  64483. get: function () {
  64484. return this.imageProcessingConfiguration.vignetteColor;
  64485. },
  64486. /**
  64487. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64488. * if vignetteEnabled is set to true.
  64489. */
  64490. set: function (value) {
  64491. this.imageProcessingConfiguration.vignetteColor = value;
  64492. },
  64493. enumerable: true,
  64494. configurable: true
  64495. });
  64496. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  64497. /**
  64498. * Gets Camera field of view used by the Vignette effect.
  64499. */
  64500. get: function () {
  64501. return this.imageProcessingConfiguration.vignetteCameraFov;
  64502. },
  64503. /**
  64504. * Sets Camera field of view used by the Vignette effect.
  64505. */
  64506. set: function (value) {
  64507. this.imageProcessingConfiguration.vignetteCameraFov = value;
  64508. },
  64509. enumerable: true,
  64510. configurable: true
  64511. });
  64512. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  64513. /**
  64514. * Gets the vignette blend mode allowing different kind of effect.
  64515. */
  64516. get: function () {
  64517. return this.imageProcessingConfiguration.vignetteBlendMode;
  64518. },
  64519. /**
  64520. * Sets the vignette blend mode allowing different kind of effect.
  64521. */
  64522. set: function (value) {
  64523. this.imageProcessingConfiguration.vignetteBlendMode = value;
  64524. },
  64525. enumerable: true,
  64526. configurable: true
  64527. });
  64528. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  64529. /**
  64530. * Gets wether the vignette effect is enabled.
  64531. */
  64532. get: function () {
  64533. return this.imageProcessingConfiguration.vignetteEnabled;
  64534. },
  64535. /**
  64536. * Sets wether the vignette effect is enabled.
  64537. */
  64538. set: function (value) {
  64539. this.imageProcessingConfiguration.vignetteEnabled = value;
  64540. },
  64541. enumerable: true,
  64542. configurable: true
  64543. });
  64544. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  64545. /**
  64546. * Gets wether the input of the processing is in Gamma or Linear Space.
  64547. */
  64548. get: function () {
  64549. return this._fromLinearSpace;
  64550. },
  64551. /**
  64552. * Sets wether the input of the processing is in Gamma or Linear Space.
  64553. */
  64554. set: function (value) {
  64555. if (this._fromLinearSpace === value) {
  64556. return;
  64557. }
  64558. this._fromLinearSpace = value;
  64559. this._updateParameters();
  64560. },
  64561. enumerable: true,
  64562. configurable: true
  64563. });
  64564. ImageProcessingPostProcess.prototype.getClassName = function () {
  64565. return "ImageProcessingPostProcess";
  64566. };
  64567. ImageProcessingPostProcess.prototype._updateParameters = function () {
  64568. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  64569. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  64570. var defines = "";
  64571. for (var define in this._defines) {
  64572. if (this._defines[define]) {
  64573. defines += "#define " + define + ";\r\n";
  64574. }
  64575. }
  64576. var samplers = ["textureSampler"];
  64577. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  64578. var uniforms = ["scale"];
  64579. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  64580. this.updateEffect(defines, uniforms, samplers);
  64581. };
  64582. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  64583. _super.prototype.dispose.call(this, camera);
  64584. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64585. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64586. }
  64587. this.imageProcessingConfiguration.applyByPostProcess = false;
  64588. };
  64589. __decorate([
  64590. BABYLON.serialize()
  64591. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  64592. return ImageProcessingPostProcess;
  64593. }(BABYLON.PostProcess));
  64594. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  64595. })(BABYLON || (BABYLON = {}));
  64596. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  64597. var BABYLON;
  64598. (function (BABYLON) {
  64599. var BlurPostProcess = /** @class */ (function (_super) {
  64600. __extends(BlurPostProcess, _super);
  64601. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  64602. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64603. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64604. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  64605. _this.direction = direction;
  64606. _this._packedFloat = false;
  64607. _this.onApplyObservable.add(function (effect) {
  64608. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  64609. });
  64610. _this.kernel = kernel;
  64611. return _this;
  64612. }
  64613. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  64614. /**
  64615. * Gets the length in pixels of the blur sample region
  64616. */
  64617. get: function () {
  64618. return this._idealKernel;
  64619. },
  64620. /**
  64621. * Sets the length in pixels of the blur sample region
  64622. */
  64623. set: function (v) {
  64624. if (this._idealKernel === v) {
  64625. return;
  64626. }
  64627. v = Math.max(v, 1);
  64628. this._idealKernel = v;
  64629. this._kernel = this._nearestBestKernel(v);
  64630. this._updateParameters();
  64631. },
  64632. enumerable: true,
  64633. configurable: true
  64634. });
  64635. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  64636. /**
  64637. * Gets wether or not the blur is unpacking/repacking floats
  64638. */
  64639. get: function () {
  64640. return this._packedFloat;
  64641. },
  64642. /**
  64643. * Sets wether or not the blur needs to unpack/repack floats
  64644. */
  64645. set: function (v) {
  64646. if (this._packedFloat === v) {
  64647. return;
  64648. }
  64649. this._packedFloat = v;
  64650. this._updateParameters();
  64651. },
  64652. enumerable: true,
  64653. configurable: true
  64654. });
  64655. BlurPostProcess.prototype._updateParameters = function () {
  64656. // Generate sampling offsets and weights
  64657. var N = this._kernel;
  64658. var centerIndex = (N - 1) / 2;
  64659. // Generate Gaussian sampling weights over kernel
  64660. var offsets = [];
  64661. var weights = [];
  64662. var totalWeight = 0;
  64663. for (var i = 0; i < N; i++) {
  64664. var u = i / (N - 1);
  64665. var w = this._gaussianWeight(u * 2.0 - 1);
  64666. offsets[i] = (i - centerIndex);
  64667. weights[i] = w;
  64668. totalWeight += w;
  64669. }
  64670. // Normalize weights
  64671. for (var i = 0; i < weights.length; i++) {
  64672. weights[i] /= totalWeight;
  64673. }
  64674. // Optimize: combine samples to take advantage of hardware linear sampling
  64675. // Walk from left to center, combining pairs (symmetrically)
  64676. var linearSamplingWeights = [];
  64677. var linearSamplingOffsets = [];
  64678. var linearSamplingMap = [];
  64679. for (var i = 0; i <= centerIndex; i += 2) {
  64680. var j = Math.min(i + 1, Math.floor(centerIndex));
  64681. var singleCenterSample = i === j;
  64682. if (singleCenterSample) {
  64683. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64684. }
  64685. else {
  64686. var sharedCell = j === centerIndex;
  64687. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  64688. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  64689. if (offsetLinear === 0) {
  64690. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  64691. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  64692. }
  64693. else {
  64694. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  64695. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  64696. }
  64697. }
  64698. }
  64699. for (var i = 0; i < linearSamplingMap.length; i++) {
  64700. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  64701. linearSamplingWeights[i] = linearSamplingMap[i].w;
  64702. }
  64703. // Replace with optimized
  64704. offsets = linearSamplingOffsets;
  64705. weights = linearSamplingWeights;
  64706. // Generate shaders
  64707. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  64708. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  64709. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  64710. var defines = "";
  64711. for (var i = 0; i < varyingCount; i++) {
  64712. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  64713. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  64714. }
  64715. var depCount = 0;
  64716. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  64717. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  64718. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  64719. depCount++;
  64720. }
  64721. if (this.packedFloat) {
  64722. defines += "#define PACKEDFLOAT 1";
  64723. }
  64724. this.updateEffect(defines, null, null, {
  64725. varyingCount: varyingCount,
  64726. depCount: depCount
  64727. });
  64728. };
  64729. /**
  64730. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  64731. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  64732. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  64733. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  64734. * The gaps between physical kernels are compensated for in the weighting of the samples
  64735. * @param idealKernel Ideal blur kernel.
  64736. * @return Nearest best kernel.
  64737. */
  64738. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  64739. var v = Math.round(idealKernel);
  64740. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  64741. var k = _a[_i];
  64742. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  64743. return Math.max(k, 3);
  64744. }
  64745. }
  64746. return Math.max(v, 3);
  64747. };
  64748. /**
  64749. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  64750. * @param x The point on the Gaussian distribution to sample.
  64751. * @return the value of the Gaussian function at x.
  64752. */
  64753. BlurPostProcess.prototype._gaussianWeight = function (x) {
  64754. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  64755. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  64756. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  64757. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  64758. // truncated at around 1.3% of peak strength.
  64759. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  64760. var sigma = (1 / 3);
  64761. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  64762. var exponent = -((x * x) / (2.0 * sigma * sigma));
  64763. var weight = (1.0 / denominator) * Math.exp(exponent);
  64764. return weight;
  64765. };
  64766. /**
  64767. * Generates a string that can be used as a floating point number in GLSL.
  64768. * @param x Value to print.
  64769. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  64770. * @return GLSL float string.
  64771. */
  64772. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  64773. if (decimalFigures === void 0) { decimalFigures = 8; }
  64774. return x.toFixed(decimalFigures).replace(/0+$/, '');
  64775. };
  64776. return BlurPostProcess;
  64777. }(BABYLON.PostProcess));
  64778. BABYLON.BlurPostProcess = BlurPostProcess;
  64779. })(BABYLON || (BABYLON = {}));
  64780. //# sourceMappingURL=babylon.blurPostProcess.js.map
  64781. var BABYLON;
  64782. (function (BABYLON) {
  64783. var Bone = /** @class */ (function (_super) {
  64784. __extends(Bone, _super);
  64785. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  64786. if (parentBone === void 0) { parentBone = null; }
  64787. if (localMatrix === void 0) { localMatrix = null; }
  64788. if (restPose === void 0) { restPose = null; }
  64789. if (baseMatrix === void 0) { baseMatrix = null; }
  64790. if (index === void 0) { index = null; }
  64791. var _this = _super.call(this, name, skeleton.getScene()) || this;
  64792. _this.name = name;
  64793. _this.children = new Array();
  64794. _this.animations = new Array();
  64795. // Set this value to map this bone to a different index in the transform matrices.
  64796. // Set this value to -1 to exclude the bone from the transform matrices.
  64797. _this._index = null;
  64798. _this._worldTransform = new BABYLON.Matrix();
  64799. _this._absoluteTransform = new BABYLON.Matrix();
  64800. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  64801. _this._scaleMatrix = BABYLON.Matrix.Identity();
  64802. _this._scaleVector = BABYLON.Vector3.One();
  64803. _this._negateScaleChildren = BABYLON.Vector3.One();
  64804. _this._scalingDeterminant = 1;
  64805. _this._skeleton = skeleton;
  64806. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  64807. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  64808. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  64809. _this._index = index;
  64810. skeleton.bones.push(_this);
  64811. _this.setParent(parentBone, false);
  64812. _this._updateDifferenceMatrix();
  64813. return _this;
  64814. }
  64815. Object.defineProperty(Bone.prototype, "_matrix", {
  64816. get: function () {
  64817. return this._localMatrix;
  64818. },
  64819. set: function (val) {
  64820. if (this._localMatrix) {
  64821. this._localMatrix.copyFrom(val);
  64822. }
  64823. else {
  64824. this._localMatrix = val;
  64825. }
  64826. },
  64827. enumerable: true,
  64828. configurable: true
  64829. });
  64830. // Members
  64831. Bone.prototype.getSkeleton = function () {
  64832. return this._skeleton;
  64833. };
  64834. Bone.prototype.getParent = function () {
  64835. return this._parent;
  64836. };
  64837. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  64838. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  64839. if (this._parent === parent) {
  64840. return;
  64841. }
  64842. if (this._parent) {
  64843. var index = this._parent.children.indexOf(this);
  64844. if (index !== -1) {
  64845. this._parent.children.splice(index, 1);
  64846. }
  64847. }
  64848. this._parent = parent;
  64849. if (this._parent) {
  64850. this._parent.children.push(this);
  64851. }
  64852. if (updateDifferenceMatrix) {
  64853. this._updateDifferenceMatrix();
  64854. }
  64855. };
  64856. Bone.prototype.getLocalMatrix = function () {
  64857. return this._localMatrix;
  64858. };
  64859. Bone.prototype.getBaseMatrix = function () {
  64860. return this._baseMatrix;
  64861. };
  64862. Bone.prototype.getRestPose = function () {
  64863. return this._restPose;
  64864. };
  64865. Bone.prototype.returnToRest = function () {
  64866. this.updateMatrix(this._restPose.clone());
  64867. };
  64868. Bone.prototype.getWorldMatrix = function () {
  64869. return this._worldTransform;
  64870. };
  64871. Bone.prototype.getInvertedAbsoluteTransform = function () {
  64872. return this._invertedAbsoluteTransform;
  64873. };
  64874. Bone.prototype.getAbsoluteTransform = function () {
  64875. return this._absoluteTransform;
  64876. };
  64877. Object.defineProperty(Bone.prototype, "position", {
  64878. // Properties (matches AbstractMesh properties)
  64879. get: function () {
  64880. return this.getPosition();
  64881. },
  64882. set: function (newPosition) {
  64883. this.setPosition(newPosition);
  64884. },
  64885. enumerable: true,
  64886. configurable: true
  64887. });
  64888. Object.defineProperty(Bone.prototype, "rotation", {
  64889. get: function () {
  64890. return this.getRotation();
  64891. },
  64892. set: function (newRotation) {
  64893. this.setRotation(newRotation);
  64894. },
  64895. enumerable: true,
  64896. configurable: true
  64897. });
  64898. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  64899. get: function () {
  64900. return this.getRotationQuaternion();
  64901. },
  64902. set: function (newRotation) {
  64903. this.setRotationQuaternion(newRotation);
  64904. },
  64905. enumerable: true,
  64906. configurable: true
  64907. });
  64908. Object.defineProperty(Bone.prototype, "scaling", {
  64909. get: function () {
  64910. return this.getScale();
  64911. },
  64912. set: function (newScaling) {
  64913. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  64914. },
  64915. enumerable: true,
  64916. configurable: true
  64917. });
  64918. // Methods
  64919. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  64920. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  64921. this._baseMatrix = matrix.clone();
  64922. this._localMatrix = matrix.clone();
  64923. this._skeleton._markAsDirty();
  64924. if (updateDifferenceMatrix) {
  64925. this._updateDifferenceMatrix();
  64926. }
  64927. };
  64928. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  64929. if (!rootMatrix) {
  64930. rootMatrix = this._baseMatrix;
  64931. }
  64932. if (this._parent) {
  64933. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  64934. }
  64935. else {
  64936. this._absoluteTransform.copyFrom(rootMatrix);
  64937. }
  64938. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  64939. for (var index = 0; index < this.children.length; index++) {
  64940. this.children[index]._updateDifferenceMatrix();
  64941. }
  64942. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  64943. };
  64944. Bone.prototype.markAsDirty = function () {
  64945. this._currentRenderId++;
  64946. this._skeleton._markAsDirty();
  64947. };
  64948. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  64949. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64950. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  64951. // all animation may be coming from a library skeleton, so may need to create animation
  64952. if (this.animations.length === 0) {
  64953. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  64954. this.animations[0].setKeys([]);
  64955. }
  64956. // get animation info / verify there is such a range from the source bone
  64957. var sourceRange = source.animations[0].getRange(rangeName);
  64958. if (!sourceRange) {
  64959. return false;
  64960. }
  64961. var from = sourceRange.from;
  64962. var to = sourceRange.to;
  64963. var sourceKeys = source.animations[0].getKeys();
  64964. // rescaling prep
  64965. var sourceBoneLength = source.length;
  64966. var sourceParent = source.getParent();
  64967. var parent = this.getParent();
  64968. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  64969. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  64970. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  64971. var destKeys = this.animations[0].getKeys();
  64972. // loop vars declaration
  64973. var orig;
  64974. var origTranslation;
  64975. var mat;
  64976. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  64977. orig = sourceKeys[key];
  64978. if (orig.frame >= from && orig.frame <= to) {
  64979. if (rescaleAsRequired) {
  64980. mat = orig.value.clone();
  64981. // scale based on parent ratio, when bone has parent
  64982. if (parentScalingReqd) {
  64983. origTranslation = mat.getTranslation();
  64984. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  64985. // scale based on skeleton dimension ratio when root bone, and value is passed
  64986. }
  64987. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  64988. origTranslation = mat.getTranslation();
  64989. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  64990. // use original when root bone, and no data for skelDimensionsRatio
  64991. }
  64992. else {
  64993. mat = orig.value;
  64994. }
  64995. }
  64996. else {
  64997. mat = orig.value;
  64998. }
  64999. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65000. }
  65001. }
  65002. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65003. return true;
  65004. };
  65005. /**
  65006. * Translate the bone in local or world space.
  65007. * @param vec The amount to translate the bone.
  65008. * @param space The space that the translation is in.
  65009. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65010. */
  65011. Bone.prototype.translate = function (vec, space, mesh) {
  65012. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65013. var lm = this.getLocalMatrix();
  65014. if (space == BABYLON.Space.LOCAL) {
  65015. lm.m[12] += vec.x;
  65016. lm.m[13] += vec.y;
  65017. lm.m[14] += vec.z;
  65018. }
  65019. else {
  65020. var wm = null;
  65021. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65022. if (mesh) {
  65023. wm = mesh.getWorldMatrix();
  65024. }
  65025. this._skeleton.computeAbsoluteTransforms();
  65026. var tmat = Bone._tmpMats[0];
  65027. var tvec = Bone._tmpVecs[0];
  65028. if (this._parent) {
  65029. if (mesh && wm) {
  65030. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65031. tmat.multiplyToRef(wm, tmat);
  65032. }
  65033. else {
  65034. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65035. }
  65036. }
  65037. tmat.m[12] = 0;
  65038. tmat.m[13] = 0;
  65039. tmat.m[14] = 0;
  65040. tmat.invert();
  65041. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65042. lm.m[12] += tvec.x;
  65043. lm.m[13] += tvec.y;
  65044. lm.m[14] += tvec.z;
  65045. }
  65046. this.markAsDirty();
  65047. };
  65048. /**
  65049. * Set the postion of the bone in local or world space.
  65050. * @param position The position to set the bone.
  65051. * @param space The space that the position is in.
  65052. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65053. */
  65054. Bone.prototype.setPosition = function (position, space, mesh) {
  65055. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65056. var lm = this.getLocalMatrix();
  65057. if (space == BABYLON.Space.LOCAL) {
  65058. lm.m[12] = position.x;
  65059. lm.m[13] = position.y;
  65060. lm.m[14] = position.z;
  65061. }
  65062. else {
  65063. var wm = null;
  65064. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65065. if (mesh) {
  65066. wm = mesh.getWorldMatrix();
  65067. }
  65068. this._skeleton.computeAbsoluteTransforms();
  65069. var tmat = Bone._tmpMats[0];
  65070. var vec = Bone._tmpVecs[0];
  65071. if (this._parent) {
  65072. if (mesh && wm) {
  65073. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65074. tmat.multiplyToRef(wm, tmat);
  65075. }
  65076. else {
  65077. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65078. }
  65079. }
  65080. tmat.invert();
  65081. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65082. lm.m[12] = vec.x;
  65083. lm.m[13] = vec.y;
  65084. lm.m[14] = vec.z;
  65085. }
  65086. this.markAsDirty();
  65087. };
  65088. /**
  65089. * Set the absolute postion of the bone (world space).
  65090. * @param position The position to set the bone.
  65091. * @param mesh The mesh that this bone is attached to.
  65092. */
  65093. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65094. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65095. };
  65096. /**
  65097. * Set the scale of the bone on the x, y and z axes.
  65098. * @param x The scale of the bone on the x axis.
  65099. * @param x The scale of the bone on the y axis.
  65100. * @param z The scale of the bone on the z axis.
  65101. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65102. */
  65103. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65104. if (scaleChildren === void 0) { scaleChildren = false; }
  65105. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65106. if (!scaleChildren) {
  65107. this._negateScaleChildren.x = 1 / x;
  65108. this._negateScaleChildren.y = 1 / y;
  65109. this._negateScaleChildren.z = 1 / z;
  65110. }
  65111. this._syncScaleVector();
  65112. }
  65113. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65114. };
  65115. /**
  65116. * Scale the bone on the x, y and z axes.
  65117. * @param x The amount to scale the bone on the x axis.
  65118. * @param x The amount to scale the bone on the y axis.
  65119. * @param z The amount to scale the bone on the z axis.
  65120. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65121. */
  65122. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65123. if (scaleChildren === void 0) { scaleChildren = false; }
  65124. var locMat = this.getLocalMatrix();
  65125. var origLocMat = Bone._tmpMats[0];
  65126. origLocMat.copyFrom(locMat);
  65127. var origLocMatInv = Bone._tmpMats[1];
  65128. origLocMatInv.copyFrom(origLocMat);
  65129. origLocMatInv.invert();
  65130. var scaleMat = Bone._tmpMats[2];
  65131. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65132. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65133. this._scaleVector.x *= x;
  65134. this._scaleVector.y *= y;
  65135. this._scaleVector.z *= z;
  65136. locMat.multiplyToRef(origLocMatInv, locMat);
  65137. locMat.multiplyToRef(scaleMat, locMat);
  65138. locMat.multiplyToRef(origLocMat, locMat);
  65139. var parent = this.getParent();
  65140. if (parent) {
  65141. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65142. }
  65143. else {
  65144. this.getAbsoluteTransform().copyFrom(locMat);
  65145. }
  65146. var len = this.children.length;
  65147. scaleMat.invert();
  65148. for (var i = 0; i < len; i++) {
  65149. var child = this.children[i];
  65150. var cm = child.getLocalMatrix();
  65151. cm.multiplyToRef(scaleMat, cm);
  65152. var lm = child.getLocalMatrix();
  65153. lm.m[12] *= x;
  65154. lm.m[13] *= y;
  65155. lm.m[14] *= z;
  65156. }
  65157. this.computeAbsoluteTransforms();
  65158. if (scaleChildren) {
  65159. for (var i = 0; i < len; i++) {
  65160. this.children[i].scale(x, y, z, scaleChildren);
  65161. }
  65162. }
  65163. this.markAsDirty();
  65164. };
  65165. /**
  65166. * Set the yaw, pitch, and roll of the bone in local or world space.
  65167. * @param yaw The rotation of the bone on the y axis.
  65168. * @param pitch The rotation of the bone on the x axis.
  65169. * @param roll The rotation of the bone on the z axis.
  65170. * @param space The space that the axes of rotation are in.
  65171. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65172. */
  65173. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65174. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65175. var rotMat = Bone._tmpMats[0];
  65176. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65177. var rotMatInv = Bone._tmpMats[1];
  65178. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65179. rotMatInv.multiplyToRef(rotMat, rotMat);
  65180. this._rotateWithMatrix(rotMat, space, mesh);
  65181. };
  65182. /**
  65183. * Rotate the bone on an axis in local or world space.
  65184. * @param axis The axis to rotate the bone on.
  65185. * @param amount The amount to rotate the bone.
  65186. * @param space The space that the axis is in.
  65187. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65188. */
  65189. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65190. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65191. var rmat = Bone._tmpMats[0];
  65192. rmat.m[12] = 0;
  65193. rmat.m[13] = 0;
  65194. rmat.m[14] = 0;
  65195. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65196. this._rotateWithMatrix(rmat, space, mesh);
  65197. };
  65198. /**
  65199. * Set the rotation of the bone to a particular axis angle in local or world space.
  65200. * @param axis The axis to rotate the bone on.
  65201. * @param angle The angle that the bone should be rotated to.
  65202. * @param space The space that the axis is in.
  65203. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65204. */
  65205. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65207. var rotMat = Bone._tmpMats[0];
  65208. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65209. var rotMatInv = Bone._tmpMats[1];
  65210. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65211. rotMatInv.multiplyToRef(rotMat, rotMat);
  65212. this._rotateWithMatrix(rotMat, space, mesh);
  65213. };
  65214. /**
  65215. * Set the euler rotation of the bone in local of world space.
  65216. * @param rotation The euler rotation that the bone should be set to.
  65217. * @param space The space that the rotation is in.
  65218. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65219. */
  65220. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65221. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65222. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65223. };
  65224. /**
  65225. * Set the quaternion rotation of the bone in local of world space.
  65226. * @param quat The quaternion rotation that the bone should be set to.
  65227. * @param space The space that the rotation is in.
  65228. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65229. */
  65230. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65232. var rotMatInv = Bone._tmpMats[0];
  65233. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65234. var rotMat = Bone._tmpMats[1];
  65235. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  65236. rotMatInv.multiplyToRef(rotMat, rotMat);
  65237. this._rotateWithMatrix(rotMat, space, mesh);
  65238. };
  65239. /**
  65240. * Set the rotation matrix of the bone in local of world space.
  65241. * @param rotMat The rotation matrix that the bone should be set to.
  65242. * @param space The space that the rotation is in.
  65243. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65244. */
  65245. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  65246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65247. var rotMatInv = Bone._tmpMats[0];
  65248. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65249. var rotMat2 = Bone._tmpMats[1];
  65250. rotMat2.copyFrom(rotMat);
  65251. rotMatInv.multiplyToRef(rotMat, rotMat2);
  65252. this._rotateWithMatrix(rotMat2, space, mesh);
  65253. };
  65254. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  65255. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65256. var lmat = this.getLocalMatrix();
  65257. var lx = lmat.m[12];
  65258. var ly = lmat.m[13];
  65259. var lz = lmat.m[14];
  65260. var parent = this.getParent();
  65261. var parentScale = Bone._tmpMats[3];
  65262. var parentScaleInv = Bone._tmpMats[4];
  65263. if (parent) {
  65264. if (space == BABYLON.Space.WORLD) {
  65265. if (mesh) {
  65266. parentScale.copyFrom(mesh.getWorldMatrix());
  65267. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  65268. }
  65269. else {
  65270. parentScale.copyFrom(parent.getAbsoluteTransform());
  65271. }
  65272. }
  65273. else {
  65274. parentScale = parent._scaleMatrix;
  65275. }
  65276. parentScaleInv.copyFrom(parentScale);
  65277. parentScaleInv.invert();
  65278. lmat.multiplyToRef(parentScale, lmat);
  65279. lmat.multiplyToRef(rmat, lmat);
  65280. lmat.multiplyToRef(parentScaleInv, lmat);
  65281. }
  65282. else {
  65283. if (space == BABYLON.Space.WORLD && mesh) {
  65284. parentScale.copyFrom(mesh.getWorldMatrix());
  65285. parentScaleInv.copyFrom(parentScale);
  65286. parentScaleInv.invert();
  65287. lmat.multiplyToRef(parentScale, lmat);
  65288. lmat.multiplyToRef(rmat, lmat);
  65289. lmat.multiplyToRef(parentScaleInv, lmat);
  65290. }
  65291. else {
  65292. lmat.multiplyToRef(rmat, lmat);
  65293. }
  65294. }
  65295. lmat.m[12] = lx;
  65296. lmat.m[13] = ly;
  65297. lmat.m[14] = lz;
  65298. this.computeAbsoluteTransforms();
  65299. this.markAsDirty();
  65300. };
  65301. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  65302. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65303. if (space == BABYLON.Space.WORLD) {
  65304. var scaleMatrix = Bone._tmpMats[2];
  65305. scaleMatrix.copyFrom(this._scaleMatrix);
  65306. rotMatInv.copyFrom(this.getAbsoluteTransform());
  65307. if (mesh) {
  65308. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  65309. var meshScale = Bone._tmpMats[3];
  65310. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  65311. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  65312. }
  65313. rotMatInv.invert();
  65314. scaleMatrix.m[0] *= this._scalingDeterminant;
  65315. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65316. }
  65317. else {
  65318. rotMatInv.copyFrom(this.getLocalMatrix());
  65319. rotMatInv.invert();
  65320. var scaleMatrix = Bone._tmpMats[2];
  65321. scaleMatrix.copyFrom(this._scaleMatrix);
  65322. if (this._parent) {
  65323. var pscaleMatrix = Bone._tmpMats[3];
  65324. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  65325. pscaleMatrix.invert();
  65326. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  65327. }
  65328. else {
  65329. scaleMatrix.m[0] *= this._scalingDeterminant;
  65330. }
  65331. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65332. }
  65333. };
  65334. /**
  65335. * Get the scale of the bone
  65336. * @returns the scale of the bone
  65337. */
  65338. Bone.prototype.getScale = function () {
  65339. return this._scaleVector.clone();
  65340. };
  65341. /**
  65342. * Copy the scale of the bone to a vector3.
  65343. * @param result The vector3 to copy the scale to
  65344. */
  65345. Bone.prototype.getScaleToRef = function (result) {
  65346. result.copyFrom(this._scaleVector);
  65347. };
  65348. /**
  65349. * Get the position of the bone in local or world space.
  65350. * @param space The space that the returned position is in.
  65351. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65352. * @returns The position of the bone
  65353. */
  65354. Bone.prototype.getPosition = function (space, mesh) {
  65355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65356. if (mesh === void 0) { mesh = null; }
  65357. var pos = BABYLON.Vector3.Zero();
  65358. this.getPositionToRef(space, mesh, pos);
  65359. return pos;
  65360. };
  65361. /**
  65362. * Copy the position of the bone to a vector3 in local or world space.
  65363. * @param space The space that the returned position is in.
  65364. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65365. * @param result The vector3 to copy the position to.
  65366. */
  65367. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  65368. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65369. if (space == BABYLON.Space.LOCAL) {
  65370. var lm = this.getLocalMatrix();
  65371. result.x = lm.m[12];
  65372. result.y = lm.m[13];
  65373. result.z = lm.m[14];
  65374. }
  65375. else {
  65376. var wm = null;
  65377. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65378. if (mesh) {
  65379. wm = mesh.getWorldMatrix();
  65380. }
  65381. this._skeleton.computeAbsoluteTransforms();
  65382. var tmat = Bone._tmpMats[0];
  65383. if (mesh && wm) {
  65384. tmat.copyFrom(this.getAbsoluteTransform());
  65385. tmat.multiplyToRef(wm, tmat);
  65386. }
  65387. else {
  65388. tmat = this.getAbsoluteTransform();
  65389. }
  65390. result.x = tmat.m[12];
  65391. result.y = tmat.m[13];
  65392. result.z = tmat.m[14];
  65393. }
  65394. };
  65395. /**
  65396. * Get the absolute position of the bone (world space).
  65397. * @param mesh The mesh that this bone is attached to.
  65398. * @returns The absolute position of the bone
  65399. */
  65400. Bone.prototype.getAbsolutePosition = function (mesh) {
  65401. if (mesh === void 0) { mesh = null; }
  65402. var pos = BABYLON.Vector3.Zero();
  65403. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  65404. return pos;
  65405. };
  65406. /**
  65407. * Copy the absolute position of the bone (world space) to the result param.
  65408. * @param mesh The mesh that this bone is attached to.
  65409. * @param result The vector3 to copy the absolute position to.
  65410. */
  65411. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  65412. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  65413. };
  65414. /**
  65415. * Compute the absolute transforms of this bone and its children.
  65416. */
  65417. Bone.prototype.computeAbsoluteTransforms = function () {
  65418. if (this._parent) {
  65419. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65420. }
  65421. else {
  65422. this._absoluteTransform.copyFrom(this._localMatrix);
  65423. var poseMatrix = this._skeleton.getPoseMatrix();
  65424. if (poseMatrix) {
  65425. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  65426. }
  65427. }
  65428. var children = this.children;
  65429. var len = children.length;
  65430. for (var i = 0; i < len; i++) {
  65431. children[i].computeAbsoluteTransforms();
  65432. }
  65433. };
  65434. Bone.prototype._syncScaleVector = function () {
  65435. var lm = this.getLocalMatrix();
  65436. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  65437. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  65438. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  65439. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  65440. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  65441. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  65442. this._scaleVector.x = xs * Math.sqrt(xsq);
  65443. this._scaleVector.y = ys * Math.sqrt(ysq);
  65444. this._scaleVector.z = zs * Math.sqrt(zsq);
  65445. if (this._parent) {
  65446. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  65447. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  65448. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  65449. }
  65450. 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);
  65451. };
  65452. /**
  65453. * Get the world direction from an axis that is in the local space of the bone.
  65454. * @param localAxis The local direction that is used to compute the world direction.
  65455. * @param mesh The mesh that this bone is attached to.
  65456. * @returns The world direction
  65457. */
  65458. Bone.prototype.getDirection = function (localAxis, mesh) {
  65459. if (mesh === void 0) { mesh = null; }
  65460. var result = BABYLON.Vector3.Zero();
  65461. this.getDirectionToRef(localAxis, mesh, result);
  65462. return result;
  65463. };
  65464. /**
  65465. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  65466. * @param localAxis The local direction that is used to compute the world direction.
  65467. * @param mesh The mesh that this bone is attached to.
  65468. * @param result The vector3 that the world direction will be copied to.
  65469. */
  65470. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  65471. if (mesh === void 0) { mesh = null; }
  65472. var wm = null;
  65473. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65474. if (mesh) {
  65475. wm = mesh.getWorldMatrix();
  65476. }
  65477. this._skeleton.computeAbsoluteTransforms();
  65478. var mat = Bone._tmpMats[0];
  65479. mat.copyFrom(this.getAbsoluteTransform());
  65480. if (mesh && wm) {
  65481. mat.multiplyToRef(wm, mat);
  65482. }
  65483. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  65484. result.normalize();
  65485. };
  65486. /**
  65487. * Get the euler rotation of the bone in local or world space.
  65488. * @param space The space that the rotation should be in.
  65489. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65490. * @returns The euler rotation
  65491. */
  65492. Bone.prototype.getRotation = function (space, mesh) {
  65493. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65494. if (mesh === void 0) { mesh = null; }
  65495. var result = BABYLON.Vector3.Zero();
  65496. this.getRotationToRef(space, mesh, result);
  65497. return result;
  65498. };
  65499. /**
  65500. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  65501. * @param space The space that the rotation should be in.
  65502. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65503. * @param result The vector3 that the rotation should be copied to.
  65504. */
  65505. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  65506. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65507. if (mesh === void 0) { mesh = null; }
  65508. var quat = Bone._tmpQuat;
  65509. this.getRotationQuaternionToRef(space, mesh, quat);
  65510. quat.toEulerAnglesToRef(result);
  65511. };
  65512. /**
  65513. * Get the quaternion rotation of the bone in either local or world space.
  65514. * @param space The space that the rotation should be in.
  65515. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65516. * @returns The quaternion rotation
  65517. */
  65518. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  65519. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65520. if (mesh === void 0) { mesh = null; }
  65521. var result = BABYLON.Quaternion.Identity();
  65522. this.getRotationQuaternionToRef(space, mesh, result);
  65523. return result;
  65524. };
  65525. /**
  65526. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  65527. * @param space The space that the rotation should be in.
  65528. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65529. * @param result The quaternion that the rotation should be copied to.
  65530. */
  65531. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  65532. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65533. if (mesh === void 0) { mesh = null; }
  65534. if (space == BABYLON.Space.LOCAL) {
  65535. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65536. }
  65537. else {
  65538. var mat = Bone._tmpMats[0];
  65539. var amat = this.getAbsoluteTransform();
  65540. if (mesh) {
  65541. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65542. }
  65543. else {
  65544. mat.copyFrom(amat);
  65545. }
  65546. mat.m[0] *= this._scalingDeterminant;
  65547. mat.m[1] *= this._scalingDeterminant;
  65548. mat.m[2] *= this._scalingDeterminant;
  65549. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65550. }
  65551. };
  65552. /**
  65553. * Get the rotation matrix of the bone in local or world space.
  65554. * @param space The space that the rotation should be in.
  65555. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65556. * @returns The rotation matrix
  65557. */
  65558. Bone.prototype.getRotationMatrix = function (space, mesh) {
  65559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65560. var result = BABYLON.Matrix.Identity();
  65561. this.getRotationMatrixToRef(space, mesh, result);
  65562. return result;
  65563. };
  65564. /**
  65565. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  65566. * @param space The space that the rotation should be in.
  65567. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65568. * @param result The quaternion that the rotation should be copied to.
  65569. */
  65570. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  65571. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65572. if (space == BABYLON.Space.LOCAL) {
  65573. this.getLocalMatrix().getRotationMatrixToRef(result);
  65574. }
  65575. else {
  65576. var mat = Bone._tmpMats[0];
  65577. var amat = this.getAbsoluteTransform();
  65578. if (mesh) {
  65579. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65580. }
  65581. else {
  65582. mat.copyFrom(amat);
  65583. }
  65584. mat.m[0] *= this._scalingDeterminant;
  65585. mat.m[1] *= this._scalingDeterminant;
  65586. mat.m[2] *= this._scalingDeterminant;
  65587. mat.getRotationMatrixToRef(result);
  65588. }
  65589. };
  65590. /**
  65591. * Get the world position of a point that is in the local space of the bone.
  65592. * @param position The local position
  65593. * @param mesh The mesh that this bone is attached to.
  65594. * @returns The world position
  65595. */
  65596. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  65597. if (mesh === void 0) { mesh = null; }
  65598. var result = BABYLON.Vector3.Zero();
  65599. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  65600. return result;
  65601. };
  65602. /**
  65603. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  65604. * @param position The local position
  65605. * @param mesh The mesh that this bone is attached to.
  65606. * @param result The vector3 that the world position should be copied to.
  65607. */
  65608. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  65609. if (mesh === void 0) { mesh = null; }
  65610. var wm = null;
  65611. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65612. if (mesh) {
  65613. wm = mesh.getWorldMatrix();
  65614. }
  65615. this._skeleton.computeAbsoluteTransforms();
  65616. var tmat = Bone._tmpMats[0];
  65617. if (mesh && wm) {
  65618. tmat.copyFrom(this.getAbsoluteTransform());
  65619. tmat.multiplyToRef(wm, tmat);
  65620. }
  65621. else {
  65622. tmat = this.getAbsoluteTransform();
  65623. }
  65624. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65625. };
  65626. /**
  65627. * Get the local position of a point that is in world space.
  65628. * @param position The world position
  65629. * @param mesh The mesh that this bone is attached to.
  65630. * @returns The local position
  65631. */
  65632. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  65633. if (mesh === void 0) { mesh = null; }
  65634. var result = BABYLON.Vector3.Zero();
  65635. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  65636. return result;
  65637. };
  65638. /**
  65639. * Get the local position of a point that is in world space and copy it to the result param.
  65640. * @param position The world position
  65641. * @param mesh The mesh that this bone is attached to.
  65642. * @param result The vector3 that the local position should be copied to.
  65643. */
  65644. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  65645. if (mesh === void 0) { mesh = null; }
  65646. var wm = null;
  65647. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65648. if (mesh) {
  65649. wm = mesh.getWorldMatrix();
  65650. }
  65651. this._skeleton.computeAbsoluteTransforms();
  65652. var tmat = Bone._tmpMats[0];
  65653. tmat.copyFrom(this.getAbsoluteTransform());
  65654. if (mesh && wm) {
  65655. tmat.multiplyToRef(wm, tmat);
  65656. }
  65657. tmat.invert();
  65658. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  65659. };
  65660. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65661. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  65662. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  65663. return Bone;
  65664. }(BABYLON.Node));
  65665. BABYLON.Bone = Bone;
  65666. })(BABYLON || (BABYLON = {}));
  65667. //# sourceMappingURL=babylon.bone.js.map
  65668. var BABYLON;
  65669. (function (BABYLON) {
  65670. var BoneIKController = /** @class */ (function () {
  65671. function BoneIKController(mesh, bone, options) {
  65672. this.targetPosition = BABYLON.Vector3.Zero();
  65673. this.poleTargetPosition = BABYLON.Vector3.Zero();
  65674. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  65675. this.poleAngle = 0;
  65676. this.slerpAmount = 1;
  65677. this._bone1Quat = BABYLON.Quaternion.Identity();
  65678. this._bone1Mat = BABYLON.Matrix.Identity();
  65679. this._bone2Ang = Math.PI;
  65680. this._maxAngle = Math.PI;
  65681. this._rightHandedSystem = false;
  65682. this._bendAxis = BABYLON.Vector3.Right();
  65683. this._slerping = false;
  65684. this._adjustRoll = 0;
  65685. this._bone2 = bone;
  65686. this._bone1 = bone.getParent();
  65687. if (!this._bone1) {
  65688. return;
  65689. }
  65690. this.mesh = mesh;
  65691. var bonePos = bone.getPosition();
  65692. if (bone.getAbsoluteTransform().determinant() > 0) {
  65693. this._rightHandedSystem = true;
  65694. this._bendAxis.x = 0;
  65695. this._bendAxis.y = 0;
  65696. this._bendAxis.z = -1;
  65697. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  65698. this._adjustRoll = Math.PI * .5;
  65699. this._bendAxis.z = 1;
  65700. }
  65701. }
  65702. if (this._bone1.length) {
  65703. var boneScale1 = this._bone1.getScale();
  65704. var boneScale2 = this._bone2.getScale();
  65705. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  65706. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  65707. }
  65708. else if (this._bone1.children[0]) {
  65709. mesh.computeWorldMatrix(true);
  65710. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  65711. var pos2 = this._bone2.getAbsolutePosition(mesh);
  65712. var pos3 = this._bone1.getAbsolutePosition(mesh);
  65713. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  65714. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  65715. }
  65716. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  65717. this.maxAngle = Math.PI;
  65718. if (options) {
  65719. if (options.targetMesh) {
  65720. this.targetMesh = options.targetMesh;
  65721. this.targetMesh.computeWorldMatrix(true);
  65722. }
  65723. if (options.poleTargetMesh) {
  65724. this.poleTargetMesh = options.poleTargetMesh;
  65725. this.poleTargetMesh.computeWorldMatrix(true);
  65726. }
  65727. else if (options.poleTargetBone) {
  65728. this.poleTargetBone = options.poleTargetBone;
  65729. }
  65730. else if (this._bone1.getParent()) {
  65731. this.poleTargetBone = this._bone1.getParent();
  65732. }
  65733. if (options.poleTargetLocalOffset) {
  65734. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  65735. }
  65736. if (options.poleAngle) {
  65737. this.poleAngle = options.poleAngle;
  65738. }
  65739. if (options.bendAxis) {
  65740. this._bendAxis.copyFrom(options.bendAxis);
  65741. }
  65742. if (options.maxAngle) {
  65743. this.maxAngle = options.maxAngle;
  65744. }
  65745. if (options.slerpAmount) {
  65746. this.slerpAmount = options.slerpAmount;
  65747. }
  65748. }
  65749. }
  65750. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  65751. get: function () {
  65752. return this._maxAngle;
  65753. },
  65754. set: function (value) {
  65755. this._setMaxAngle(value);
  65756. },
  65757. enumerable: true,
  65758. configurable: true
  65759. });
  65760. BoneIKController.prototype._setMaxAngle = function (ang) {
  65761. if (ang < 0) {
  65762. ang = 0;
  65763. }
  65764. if (ang > Math.PI || ang == undefined) {
  65765. ang = Math.PI;
  65766. }
  65767. this._maxAngle = ang;
  65768. var a = this._bone1Length;
  65769. var b = this._bone2Length;
  65770. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  65771. };
  65772. BoneIKController.prototype.update = function () {
  65773. var bone1 = this._bone1;
  65774. if (!bone1) {
  65775. return;
  65776. }
  65777. var target = this.targetPosition;
  65778. var poleTarget = this.poleTargetPosition;
  65779. var mat1 = BoneIKController._tmpMats[0];
  65780. var mat2 = BoneIKController._tmpMats[1];
  65781. if (this.targetMesh) {
  65782. target.copyFrom(this.targetMesh.getAbsolutePosition());
  65783. }
  65784. if (this.poleTargetBone) {
  65785. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  65786. }
  65787. else if (this.poleTargetMesh) {
  65788. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  65789. }
  65790. var bonePos = BoneIKController._tmpVecs[0];
  65791. var zaxis = BoneIKController._tmpVecs[1];
  65792. var xaxis = BoneIKController._tmpVecs[2];
  65793. var yaxis = BoneIKController._tmpVecs[3];
  65794. var upAxis = BoneIKController._tmpVecs[4];
  65795. var _tmpQuat = BoneIKController._tmpQuat;
  65796. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  65797. poleTarget.subtractToRef(bonePos, upAxis);
  65798. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  65799. upAxis.y = 1;
  65800. }
  65801. else {
  65802. upAxis.normalize();
  65803. }
  65804. target.subtractToRef(bonePos, yaxis);
  65805. yaxis.normalize();
  65806. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  65807. zaxis.normalize();
  65808. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  65809. xaxis.normalize();
  65810. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  65811. var a = this._bone1Length;
  65812. var b = this._bone2Length;
  65813. var c = BABYLON.Vector3.Distance(bonePos, target);
  65814. if (this._maxReach > 0) {
  65815. c = Math.min(this._maxReach, c);
  65816. }
  65817. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  65818. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  65819. if (acosa > 1) {
  65820. acosa = 1;
  65821. }
  65822. if (acosb > 1) {
  65823. acosb = 1;
  65824. }
  65825. if (acosa < -1) {
  65826. acosa = -1;
  65827. }
  65828. if (acosb < -1) {
  65829. acosb = -1;
  65830. }
  65831. var angA = Math.acos(acosa);
  65832. var angB = Math.acos(acosb);
  65833. var angC = -angA - angB;
  65834. if (this._rightHandedSystem) {
  65835. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  65836. mat2.multiplyToRef(mat1, mat1);
  65837. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  65838. mat2.multiplyToRef(mat1, mat1);
  65839. }
  65840. else {
  65841. var _tmpVec = BoneIKController._tmpVecs[5];
  65842. _tmpVec.copyFrom(this._bendAxis);
  65843. _tmpVec.x *= -1;
  65844. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  65845. mat2.multiplyToRef(mat1, mat1);
  65846. }
  65847. if (this.poleAngle) {
  65848. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  65849. mat1.multiplyToRef(mat2, mat1);
  65850. }
  65851. if (this._bone1) {
  65852. if (this.slerpAmount < 1) {
  65853. if (!this._slerping) {
  65854. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  65855. }
  65856. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  65857. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  65858. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  65859. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  65860. this._slerping = true;
  65861. }
  65862. else {
  65863. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  65864. this._bone1Mat.copyFrom(mat1);
  65865. this._slerping = false;
  65866. }
  65867. }
  65868. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  65869. this._bone2Ang = angC;
  65870. };
  65871. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65872. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  65873. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  65874. return BoneIKController;
  65875. }());
  65876. BABYLON.BoneIKController = BoneIKController;
  65877. })(BABYLON || (BABYLON = {}));
  65878. //# sourceMappingURL=babylon.boneIKController.js.map
  65879. var BABYLON;
  65880. (function (BABYLON) {
  65881. var BoneLookController = /** @class */ (function () {
  65882. /**
  65883. * Create a BoneLookController
  65884. * @param mesh the mesh that the bone belongs to
  65885. * @param bone the bone that will be looking to the target
  65886. * @param target the target Vector3 to look at
  65887. * @param settings optional settings:
  65888. * - maxYaw: the maximum angle the bone will yaw to
  65889. * - minYaw: the minimum angle the bone will yaw to
  65890. * - maxPitch: the maximum angle the bone will pitch to
  65891. * - minPitch: the minimum angle the bone will yaw to
  65892. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  65893. * - upAxis: the up axis of the coordinate system
  65894. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  65895. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  65896. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  65897. * - adjustYaw: used to make an adjustment to the yaw of the bone
  65898. * - adjustPitch: used to make an adjustment to the pitch of the bone
  65899. * - adjustRoll: used to make an adjustment to the roll of the bone
  65900. **/
  65901. function BoneLookController(mesh, bone, target, options) {
  65902. /**
  65903. * The up axis of the coordinate system that is used when the bone is rotated.
  65904. */
  65905. this.upAxis = BABYLON.Vector3.Up();
  65906. /**
  65907. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  65908. */
  65909. this.upAxisSpace = BABYLON.Space.LOCAL;
  65910. /**
  65911. * Used to make an adjustment to the yaw of the bone.
  65912. */
  65913. this.adjustYaw = 0;
  65914. /**
  65915. * Used to make an adjustment to the pitch of the bone.
  65916. */
  65917. this.adjustPitch = 0;
  65918. /**
  65919. * Used to make an adjustment to the roll of the bone.
  65920. */
  65921. this.adjustRoll = 0;
  65922. /**
  65923. * 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).
  65924. */
  65925. this.slerpAmount = 1;
  65926. this._boneQuat = BABYLON.Quaternion.Identity();
  65927. this._slerping = false;
  65928. this._firstFrameSkipped = false;
  65929. this._fowardAxis = BABYLON.Vector3.Forward();
  65930. this.mesh = mesh;
  65931. this.bone = bone;
  65932. this.target = target;
  65933. if (options) {
  65934. if (options.adjustYaw) {
  65935. this.adjustYaw = options.adjustYaw;
  65936. }
  65937. if (options.adjustPitch) {
  65938. this.adjustPitch = options.adjustPitch;
  65939. }
  65940. if (options.adjustRoll) {
  65941. this.adjustRoll = options.adjustRoll;
  65942. }
  65943. if (options.maxYaw != null) {
  65944. this.maxYaw = options.maxYaw;
  65945. }
  65946. else {
  65947. this.maxYaw = Math.PI;
  65948. }
  65949. if (options.minYaw != null) {
  65950. this.minYaw = options.minYaw;
  65951. }
  65952. else {
  65953. this.minYaw = -Math.PI;
  65954. }
  65955. if (options.maxPitch != null) {
  65956. this.maxPitch = options.maxPitch;
  65957. }
  65958. else {
  65959. this.maxPitch = Math.PI;
  65960. }
  65961. if (options.minPitch != null) {
  65962. this.minPitch = options.minPitch;
  65963. }
  65964. else {
  65965. this.minPitch = -Math.PI;
  65966. }
  65967. if (options.slerpAmount != null) {
  65968. this.slerpAmount = options.slerpAmount;
  65969. }
  65970. if (options.upAxis != null) {
  65971. this.upAxis = options.upAxis;
  65972. }
  65973. if (options.upAxisSpace != null) {
  65974. this.upAxisSpace = options.upAxisSpace;
  65975. }
  65976. if (options.yawAxis != null || options.pitchAxis != null) {
  65977. var newYawAxis = BABYLON.Axis.Y;
  65978. var newPitchAxis = BABYLON.Axis.X;
  65979. if (options.yawAxis != null) {
  65980. newYawAxis = options.yawAxis.clone();
  65981. newYawAxis.normalize();
  65982. }
  65983. if (options.pitchAxis != null) {
  65984. newPitchAxis = options.pitchAxis.clone();
  65985. newPitchAxis.normalize();
  65986. }
  65987. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  65988. this._transformYawPitch = BABYLON.Matrix.Identity();
  65989. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  65990. this._transformYawPitchInv = this._transformYawPitch.clone();
  65991. this._transformYawPitch.invert();
  65992. }
  65993. }
  65994. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  65995. this.upAxisSpace = BABYLON.Space.LOCAL;
  65996. }
  65997. }
  65998. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  65999. /**
  66000. * Get/set the minimum yaw angle that the bone can look to.
  66001. */
  66002. get: function () {
  66003. return this._minYaw;
  66004. },
  66005. set: function (value) {
  66006. this._minYaw = value;
  66007. this._minYawSin = Math.sin(value);
  66008. this._minYawCos = Math.cos(value);
  66009. if (this._maxYaw != null) {
  66010. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66011. this._yawRange = this._maxYaw - this._minYaw;
  66012. }
  66013. },
  66014. enumerable: true,
  66015. configurable: true
  66016. });
  66017. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66018. /**
  66019. * Get/set the maximum yaw angle that the bone can look to.
  66020. */
  66021. get: function () {
  66022. return this._maxYaw;
  66023. },
  66024. set: function (value) {
  66025. this._maxYaw = value;
  66026. this._maxYawSin = Math.sin(value);
  66027. this._maxYawCos = Math.cos(value);
  66028. if (this._minYaw != null) {
  66029. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66030. this._yawRange = this._maxYaw - this._minYaw;
  66031. }
  66032. },
  66033. enumerable: true,
  66034. configurable: true
  66035. });
  66036. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66037. /**
  66038. * Get/set the minimum pitch angle that the bone can look to.
  66039. */
  66040. get: function () {
  66041. return this._minPitch;
  66042. },
  66043. set: function (value) {
  66044. this._minPitch = value;
  66045. this._minPitchTan = Math.tan(value);
  66046. },
  66047. enumerable: true,
  66048. configurable: true
  66049. });
  66050. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66051. /**
  66052. * Get/set the maximum pitch angle that the bone can look to.
  66053. */
  66054. get: function () {
  66055. return this._maxPitch;
  66056. },
  66057. set: function (value) {
  66058. this._maxPitch = value;
  66059. this._maxPitchTan = Math.tan(value);
  66060. },
  66061. enumerable: true,
  66062. configurable: true
  66063. });
  66064. /**
  66065. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66066. */
  66067. BoneLookController.prototype.update = function () {
  66068. //skip the first frame when slerping so that the mesh rotation is correct
  66069. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66070. this._firstFrameSkipped = true;
  66071. return;
  66072. }
  66073. var bone = this.bone;
  66074. var bonePos = BoneLookController._tmpVecs[0];
  66075. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66076. var target = this.target;
  66077. var _tmpMat1 = BoneLookController._tmpMats[0];
  66078. var _tmpMat2 = BoneLookController._tmpMats[1];
  66079. var mesh = this.mesh;
  66080. var parentBone = bone.getParent();
  66081. var upAxis = BoneLookController._tmpVecs[1];
  66082. upAxis.copyFrom(this.upAxis);
  66083. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66084. if (this._transformYawPitch) {
  66085. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66086. }
  66087. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66088. }
  66089. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66090. mesh.getDirectionToRef(upAxis, upAxis);
  66091. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66092. upAxis.normalize();
  66093. }
  66094. }
  66095. var checkYaw = false;
  66096. var checkPitch = false;
  66097. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66098. checkYaw = true;
  66099. }
  66100. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66101. checkPitch = true;
  66102. }
  66103. if (checkYaw || checkPitch) {
  66104. var spaceMat = BoneLookController._tmpMats[2];
  66105. var spaceMatInv = BoneLookController._tmpMats[3];
  66106. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66107. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66108. }
  66109. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66110. spaceMat.copyFrom(mesh.getWorldMatrix());
  66111. }
  66112. else {
  66113. var forwardAxis = BoneLookController._tmpVecs[2];
  66114. forwardAxis.copyFrom(this._fowardAxis);
  66115. if (this._transformYawPitch) {
  66116. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66117. }
  66118. if (parentBone) {
  66119. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66120. }
  66121. else {
  66122. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66123. }
  66124. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66125. rightAxis.normalize();
  66126. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66127. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66128. }
  66129. spaceMat.invertToRef(spaceMatInv);
  66130. var xzlen = null;
  66131. if (checkPitch) {
  66132. var localTarget = BoneLookController._tmpVecs[3];
  66133. target.subtractToRef(bonePos, localTarget);
  66134. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66135. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66136. var pitch = Math.atan2(localTarget.y, xzlen);
  66137. var newPitch = pitch;
  66138. if (pitch > this._maxPitch) {
  66139. localTarget.y = this._maxPitchTan * xzlen;
  66140. newPitch = this._maxPitch;
  66141. }
  66142. else if (pitch < this._minPitch) {
  66143. localTarget.y = this._minPitchTan * xzlen;
  66144. newPitch = this._minPitch;
  66145. }
  66146. if (pitch != newPitch) {
  66147. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66148. localTarget.addInPlace(bonePos);
  66149. target = localTarget;
  66150. }
  66151. }
  66152. if (checkYaw) {
  66153. var localTarget = BoneLookController._tmpVecs[4];
  66154. target.subtractToRef(bonePos, localTarget);
  66155. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66156. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66157. var newYaw = yaw;
  66158. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66159. if (xzlen == null) {
  66160. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66161. }
  66162. if (this._yawRange > Math.PI) {
  66163. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66164. localTarget.z = this._maxYawCos * xzlen;
  66165. localTarget.x = this._maxYawSin * xzlen;
  66166. newYaw = this._maxYaw;
  66167. }
  66168. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66169. localTarget.z = this._minYawCos * xzlen;
  66170. localTarget.x = this._minYawSin * xzlen;
  66171. newYaw = this._minYaw;
  66172. }
  66173. }
  66174. else {
  66175. if (yaw > this._maxYaw) {
  66176. localTarget.z = this._maxYawCos * xzlen;
  66177. localTarget.x = this._maxYawSin * xzlen;
  66178. newYaw = this._maxYaw;
  66179. }
  66180. else if (yaw < this._minYaw) {
  66181. localTarget.z = this._minYawCos * xzlen;
  66182. localTarget.x = this._minYawSin * xzlen;
  66183. newYaw = this._minYaw;
  66184. }
  66185. }
  66186. }
  66187. if (this._slerping && this._yawRange > Math.PI) {
  66188. //are we going to be crossing into the min/max region?
  66189. var boneFwd = BoneLookController._tmpVecs[8];
  66190. boneFwd.copyFrom(BABYLON.Axis.Z);
  66191. if (this._transformYawPitch) {
  66192. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66193. }
  66194. var boneRotMat = BoneLookController._tmpMats[4];
  66195. this._boneQuat.toRotationMatrix(boneRotMat);
  66196. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66197. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66198. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66199. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66200. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66201. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66202. if (angBtwTar > angBtwMidYaw) {
  66203. if (xzlen == null) {
  66204. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66205. }
  66206. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66207. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66208. if (angBtwMin < angBtwMax) {
  66209. newYaw = boneYaw + Math.PI * .75;
  66210. localTarget.z = Math.cos(newYaw) * xzlen;
  66211. localTarget.x = Math.sin(newYaw) * xzlen;
  66212. }
  66213. else {
  66214. newYaw = boneYaw - Math.PI * .75;
  66215. localTarget.z = Math.cos(newYaw) * xzlen;
  66216. localTarget.x = Math.sin(newYaw) * xzlen;
  66217. }
  66218. }
  66219. }
  66220. if (yaw != newYaw) {
  66221. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66222. localTarget.addInPlace(bonePos);
  66223. target = localTarget;
  66224. }
  66225. }
  66226. }
  66227. var zaxis = BoneLookController._tmpVecs[5];
  66228. var xaxis = BoneLookController._tmpVecs[6];
  66229. var yaxis = BoneLookController._tmpVecs[7];
  66230. var _tmpQuat = BoneLookController._tmpQuat;
  66231. target.subtractToRef(bonePos, zaxis);
  66232. zaxis.normalize();
  66233. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  66234. xaxis.normalize();
  66235. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  66236. yaxis.normalize();
  66237. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  66238. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  66239. return;
  66240. }
  66241. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  66242. return;
  66243. }
  66244. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  66245. return;
  66246. }
  66247. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  66248. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  66249. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  66250. }
  66251. if (this.slerpAmount < 1) {
  66252. if (!this._slerping) {
  66253. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  66254. }
  66255. if (this._transformYawPitch) {
  66256. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66257. }
  66258. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  66259. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  66260. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  66261. this._slerping = true;
  66262. }
  66263. else {
  66264. if (this._transformYawPitch) {
  66265. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66266. }
  66267. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  66268. this._slerping = false;
  66269. }
  66270. };
  66271. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  66272. var angDiff = ang2 - ang1;
  66273. angDiff %= Math.PI * 2;
  66274. if (angDiff > Math.PI) {
  66275. angDiff -= Math.PI * 2;
  66276. }
  66277. else if (angDiff < -Math.PI) {
  66278. angDiff += Math.PI * 2;
  66279. }
  66280. return angDiff;
  66281. };
  66282. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  66283. ang1 %= (2 * Math.PI);
  66284. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66285. ang2 %= (2 * Math.PI);
  66286. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66287. var ab = 0;
  66288. if (ang1 < ang2) {
  66289. ab = ang2 - ang1;
  66290. }
  66291. else {
  66292. ab = ang1 - ang2;
  66293. }
  66294. if (ab > Math.PI) {
  66295. ab = Math.PI * 2 - ab;
  66296. }
  66297. return ab;
  66298. };
  66299. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  66300. ang %= (2 * Math.PI);
  66301. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  66302. ang1 %= (2 * Math.PI);
  66303. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66304. ang2 %= (2 * Math.PI);
  66305. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66306. if (ang1 < ang2) {
  66307. if (ang > ang1 && ang < ang2) {
  66308. return true;
  66309. }
  66310. }
  66311. else {
  66312. if (ang > ang2 && ang < ang1) {
  66313. return true;
  66314. }
  66315. }
  66316. return false;
  66317. };
  66318. 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()];
  66319. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  66320. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66321. return BoneLookController;
  66322. }());
  66323. BABYLON.BoneLookController = BoneLookController;
  66324. })(BABYLON || (BABYLON = {}));
  66325. //# sourceMappingURL=babylon.boneLookController.js.map
  66326. var BABYLON;
  66327. (function (BABYLON) {
  66328. var Skeleton = /** @class */ (function () {
  66329. function Skeleton(name, id, scene) {
  66330. this.name = name;
  66331. this.id = id;
  66332. this.bones = new Array();
  66333. this.needInitialSkinMatrix = false;
  66334. this._isDirty = true;
  66335. this._meshesWithPoseMatrix = new Array();
  66336. this._identity = BABYLON.Matrix.Identity();
  66337. this._ranges = {};
  66338. this._lastAbsoluteTransformsUpdateId = -1;
  66339. // Events
  66340. /**
  66341. * An event triggered before computing the skeleton's matrices
  66342. * @type {BABYLON.Observable}
  66343. */
  66344. this.onBeforeComputeObservable = new BABYLON.Observable();
  66345. this.bones = [];
  66346. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66347. scene.skeletons.push(this);
  66348. //make sure it will recalculate the matrix next time prepare is called.
  66349. this._isDirty = true;
  66350. }
  66351. // Members
  66352. Skeleton.prototype.getTransformMatrices = function (mesh) {
  66353. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  66354. return mesh._bonesTransformMatrices;
  66355. }
  66356. if (!this._transformMatrices) {
  66357. this.prepare();
  66358. }
  66359. return this._transformMatrices;
  66360. };
  66361. Skeleton.prototype.getScene = function () {
  66362. return this._scene;
  66363. };
  66364. // Methods
  66365. /**
  66366. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  66367. */
  66368. Skeleton.prototype.toString = function (fullDetails) {
  66369. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  66370. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  66371. if (fullDetails) {
  66372. ret += ", Ranges: {";
  66373. var first = true;
  66374. for (var name_1 in this._ranges) {
  66375. if (first) {
  66376. ret += ", ";
  66377. first = false;
  66378. }
  66379. ret += name_1;
  66380. }
  66381. ret += "}";
  66382. }
  66383. return ret;
  66384. };
  66385. /**
  66386. * Get bone's index searching by name
  66387. * @param {string} name is bone's name to search for
  66388. * @return {number} Indice of the bone. Returns -1 if not found
  66389. */
  66390. Skeleton.prototype.getBoneIndexByName = function (name) {
  66391. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  66392. if (this.bones[boneIndex].name === name) {
  66393. return boneIndex;
  66394. }
  66395. }
  66396. return -1;
  66397. };
  66398. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  66399. // check name not already in use
  66400. if (!this._ranges[name]) {
  66401. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  66402. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66403. if (this.bones[i].animations[0]) {
  66404. this.bones[i].animations[0].createRange(name, from, to);
  66405. }
  66406. }
  66407. }
  66408. };
  66409. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  66410. if (deleteFrames === void 0) { deleteFrames = true; }
  66411. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66412. if (this.bones[i].animations[0]) {
  66413. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  66414. }
  66415. }
  66416. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  66417. };
  66418. Skeleton.prototype.getAnimationRange = function (name) {
  66419. return this._ranges[name];
  66420. };
  66421. /**
  66422. * Returns as an Array, all AnimationRanges defined on this skeleton
  66423. */
  66424. Skeleton.prototype.getAnimationRanges = function () {
  66425. var animationRanges = [];
  66426. var name;
  66427. var i = 0;
  66428. for (name in this._ranges) {
  66429. animationRanges[i] = this._ranges[name];
  66430. i++;
  66431. }
  66432. return animationRanges;
  66433. };
  66434. /**
  66435. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  66436. */
  66437. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  66438. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66439. if (this._ranges[name] || !source.getAnimationRange(name)) {
  66440. return false;
  66441. }
  66442. var ret = true;
  66443. var frameOffset = this._getHighestAnimationFrame() + 1;
  66444. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  66445. var boneDict = {};
  66446. var sourceBones = source.bones;
  66447. var nBones;
  66448. var i;
  66449. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  66450. boneDict[sourceBones[i].name] = sourceBones[i];
  66451. }
  66452. if (this.bones.length !== sourceBones.length) {
  66453. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  66454. ret = false;
  66455. }
  66456. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  66457. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  66458. var boneName = this.bones[i].name;
  66459. var sourceBone = boneDict[boneName];
  66460. if (sourceBone) {
  66461. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  66462. }
  66463. else {
  66464. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  66465. ret = false;
  66466. }
  66467. }
  66468. // do not call createAnimationRange(), since it also is done to bones, which was already done
  66469. var range = source.getAnimationRange(name);
  66470. if (range) {
  66471. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  66472. }
  66473. return ret;
  66474. };
  66475. Skeleton.prototype.returnToRest = function () {
  66476. for (var index = 0; index < this.bones.length; index++) {
  66477. this.bones[index].returnToRest();
  66478. }
  66479. };
  66480. Skeleton.prototype._getHighestAnimationFrame = function () {
  66481. var ret = 0;
  66482. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66483. if (this.bones[i].animations[0]) {
  66484. var highest = this.bones[i].animations[0].getHighestFrame();
  66485. if (ret < highest) {
  66486. ret = highest;
  66487. }
  66488. }
  66489. }
  66490. return ret;
  66491. };
  66492. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  66493. var range = this.getAnimationRange(name);
  66494. if (!range) {
  66495. return null;
  66496. }
  66497. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  66498. };
  66499. Skeleton.prototype._markAsDirty = function () {
  66500. this._isDirty = true;
  66501. };
  66502. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  66503. this._meshesWithPoseMatrix.push(mesh);
  66504. };
  66505. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  66506. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  66507. if (index > -1) {
  66508. this._meshesWithPoseMatrix.splice(index, 1);
  66509. }
  66510. };
  66511. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  66512. this.onBeforeComputeObservable.notifyObservers(this);
  66513. for (var index = 0; index < this.bones.length; index++) {
  66514. var bone = this.bones[index];
  66515. var parentBone = bone.getParent();
  66516. if (parentBone) {
  66517. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  66518. }
  66519. else {
  66520. if (initialSkinMatrix) {
  66521. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  66522. }
  66523. else {
  66524. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  66525. }
  66526. }
  66527. if (bone._index !== -1) {
  66528. var mappedIndex = bone._index === null ? index : bone._index;
  66529. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  66530. }
  66531. }
  66532. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  66533. };
  66534. Skeleton.prototype.prepare = function () {
  66535. if (!this._isDirty) {
  66536. return;
  66537. }
  66538. if (this.needInitialSkinMatrix) {
  66539. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  66540. var mesh = this._meshesWithPoseMatrix[index];
  66541. var poseMatrix = mesh.getPoseMatrix();
  66542. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  66543. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66544. }
  66545. if (this._synchronizedWithMesh !== mesh) {
  66546. this._synchronizedWithMesh = mesh;
  66547. // Prepare bones
  66548. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  66549. var bone = this.bones[boneIndex];
  66550. if (!bone.getParent()) {
  66551. var matrix = bone.getBaseMatrix();
  66552. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  66553. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  66554. }
  66555. }
  66556. }
  66557. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  66558. }
  66559. }
  66560. else {
  66561. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  66562. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66563. }
  66564. this._computeTransformMatrices(this._transformMatrices, null);
  66565. }
  66566. this._isDirty = false;
  66567. this._scene._activeBones.addCount(this.bones.length, false);
  66568. };
  66569. Skeleton.prototype.getAnimatables = function () {
  66570. if (!this._animatables || this._animatables.length !== this.bones.length) {
  66571. this._animatables = [];
  66572. for (var index = 0; index < this.bones.length; index++) {
  66573. this._animatables.push(this.bones[index]);
  66574. }
  66575. }
  66576. return this._animatables;
  66577. };
  66578. Skeleton.prototype.clone = function (name, id) {
  66579. var result = new Skeleton(name, id || name, this._scene);
  66580. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66581. for (var index = 0; index < this.bones.length; index++) {
  66582. var source = this.bones[index];
  66583. var parentBone = null;
  66584. var parent_1 = source.getParent();
  66585. if (parent_1) {
  66586. var parentIndex = this.bones.indexOf(parent_1);
  66587. parentBone = result.bones[parentIndex];
  66588. }
  66589. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  66590. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  66591. }
  66592. if (this._ranges) {
  66593. result._ranges = {};
  66594. for (var rangeName in this._ranges) {
  66595. var range = this._ranges[rangeName];
  66596. if (range) {
  66597. result._ranges[rangeName] = range.clone();
  66598. }
  66599. }
  66600. }
  66601. this._isDirty = true;
  66602. return result;
  66603. };
  66604. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  66605. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  66606. this.bones.forEach(function (bone) {
  66607. bone.animations.forEach(function (animation) {
  66608. animation.enableBlending = true;
  66609. animation.blendingSpeed = blendingSpeed;
  66610. });
  66611. });
  66612. };
  66613. Skeleton.prototype.dispose = function () {
  66614. this._meshesWithPoseMatrix = [];
  66615. // Animations
  66616. this.getScene().stopAnimation(this);
  66617. // Remove from scene
  66618. this.getScene().removeSkeleton(this);
  66619. };
  66620. Skeleton.prototype.serialize = function () {
  66621. var serializationObject = {};
  66622. serializationObject.name = this.name;
  66623. serializationObject.id = this.id;
  66624. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  66625. serializationObject.bones = [];
  66626. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  66627. for (var index = 0; index < this.bones.length; index++) {
  66628. var bone = this.bones[index];
  66629. var parent_2 = bone.getParent();
  66630. var serializedBone = {
  66631. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  66632. name: bone.name,
  66633. matrix: bone.getBaseMatrix().toArray(),
  66634. rest: bone.getRestPose().toArray()
  66635. };
  66636. serializationObject.bones.push(serializedBone);
  66637. if (bone.length) {
  66638. serializedBone.length = bone.length;
  66639. }
  66640. if (bone.animations && bone.animations.length > 0) {
  66641. serializedBone.animation = bone.animations[0].serialize();
  66642. }
  66643. serializationObject.ranges = [];
  66644. for (var name in this._ranges) {
  66645. var source = this._ranges[name];
  66646. if (!source) {
  66647. continue;
  66648. }
  66649. var range = {};
  66650. range.name = name;
  66651. range.from = source.from;
  66652. range.to = source.to;
  66653. serializationObject.ranges.push(range);
  66654. }
  66655. }
  66656. return serializationObject;
  66657. };
  66658. Skeleton.Parse = function (parsedSkeleton, scene) {
  66659. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  66660. if (parsedSkeleton.dimensionsAtRest) {
  66661. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  66662. }
  66663. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  66664. var index;
  66665. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  66666. var parsedBone = parsedSkeleton.bones[index];
  66667. var parentBone = null;
  66668. if (parsedBone.parentBoneIndex > -1) {
  66669. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  66670. }
  66671. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  66672. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  66673. if (parsedBone.length) {
  66674. bone.length = parsedBone.length;
  66675. }
  66676. if (parsedBone.animation) {
  66677. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  66678. }
  66679. }
  66680. // placed after bones, so createAnimationRange can cascade down
  66681. if (parsedSkeleton.ranges) {
  66682. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  66683. var data = parsedSkeleton.ranges[index];
  66684. skeleton.createAnimationRange(data.name, data.from, data.to);
  66685. }
  66686. }
  66687. return skeleton;
  66688. };
  66689. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  66690. if (forceUpdate === void 0) { forceUpdate = false; }
  66691. var renderId = this._scene.getRenderId();
  66692. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  66693. this.bones[0].computeAbsoluteTransforms();
  66694. this._lastAbsoluteTransformsUpdateId = renderId;
  66695. }
  66696. };
  66697. Skeleton.prototype.getPoseMatrix = function () {
  66698. var poseMatrix = null;
  66699. if (this._meshesWithPoseMatrix.length > 0) {
  66700. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  66701. }
  66702. return poseMatrix;
  66703. };
  66704. Skeleton.prototype.sortBones = function () {
  66705. var bones = new Array();
  66706. var visited = new Array(this.bones.length);
  66707. for (var index = 0; index < this.bones.length; index++) {
  66708. this._sortBones(index, bones, visited);
  66709. }
  66710. this.bones = bones;
  66711. };
  66712. Skeleton.prototype._sortBones = function (index, bones, visited) {
  66713. if (visited[index]) {
  66714. return;
  66715. }
  66716. visited[index] = true;
  66717. var bone = this.bones[index];
  66718. if (bone._index === undefined) {
  66719. bone._index = index;
  66720. }
  66721. var parentBone = bone.getParent();
  66722. if (parentBone) {
  66723. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  66724. }
  66725. bones.push(bone);
  66726. };
  66727. return Skeleton;
  66728. }());
  66729. BABYLON.Skeleton = Skeleton;
  66730. })(BABYLON || (BABYLON = {}));
  66731. //# sourceMappingURL=babylon.skeleton.js.map
  66732. var BABYLON;
  66733. (function (BABYLON) {
  66734. var SphericalPolynomial = /** @class */ (function () {
  66735. function SphericalPolynomial() {
  66736. this.x = BABYLON.Vector3.Zero();
  66737. this.y = BABYLON.Vector3.Zero();
  66738. this.z = BABYLON.Vector3.Zero();
  66739. this.xx = BABYLON.Vector3.Zero();
  66740. this.yy = BABYLON.Vector3.Zero();
  66741. this.zz = BABYLON.Vector3.Zero();
  66742. this.xy = BABYLON.Vector3.Zero();
  66743. this.yz = BABYLON.Vector3.Zero();
  66744. this.zx = BABYLON.Vector3.Zero();
  66745. }
  66746. SphericalPolynomial.prototype.addAmbient = function (color) {
  66747. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66748. this.xx = this.xx.add(colorVector);
  66749. this.yy = this.yy.add(colorVector);
  66750. this.zz = this.zz.add(colorVector);
  66751. };
  66752. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  66753. var result = new SphericalPolynomial();
  66754. result.x = harmonics.L11.scale(1.02333);
  66755. result.y = harmonics.L1_1.scale(1.02333);
  66756. result.z = harmonics.L10.scale(1.02333);
  66757. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  66758. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  66759. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  66760. result.yz = harmonics.L2_1.scale(0.858086);
  66761. result.zx = harmonics.L21.scale(0.858086);
  66762. result.xy = harmonics.L2_2.scale(0.858086);
  66763. result.scale(1.0 / Math.PI);
  66764. return result;
  66765. };
  66766. SphericalPolynomial.prototype.scale = function (scale) {
  66767. this.x = this.x.scale(scale);
  66768. this.y = this.y.scale(scale);
  66769. this.z = this.z.scale(scale);
  66770. this.xx = this.xx.scale(scale);
  66771. this.yy = this.yy.scale(scale);
  66772. this.zz = this.zz.scale(scale);
  66773. this.yz = this.yz.scale(scale);
  66774. this.zx = this.zx.scale(scale);
  66775. this.xy = this.xy.scale(scale);
  66776. };
  66777. return SphericalPolynomial;
  66778. }());
  66779. BABYLON.SphericalPolynomial = SphericalPolynomial;
  66780. var SphericalHarmonics = /** @class */ (function () {
  66781. function SphericalHarmonics() {
  66782. this.L00 = BABYLON.Vector3.Zero();
  66783. this.L1_1 = BABYLON.Vector3.Zero();
  66784. this.L10 = BABYLON.Vector3.Zero();
  66785. this.L11 = BABYLON.Vector3.Zero();
  66786. this.L2_2 = BABYLON.Vector3.Zero();
  66787. this.L2_1 = BABYLON.Vector3.Zero();
  66788. this.L20 = BABYLON.Vector3.Zero();
  66789. this.L21 = BABYLON.Vector3.Zero();
  66790. this.L22 = BABYLON.Vector3.Zero();
  66791. }
  66792. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  66793. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  66794. var c = colorVector.scale(deltaSolidAngle);
  66795. this.L00 = this.L00.add(c.scale(0.282095));
  66796. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  66797. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  66798. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  66799. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  66800. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  66801. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  66802. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  66803. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  66804. };
  66805. SphericalHarmonics.prototype.scale = function (scale) {
  66806. this.L00 = this.L00.scale(scale);
  66807. this.L1_1 = this.L1_1.scale(scale);
  66808. this.L10 = this.L10.scale(scale);
  66809. this.L11 = this.L11.scale(scale);
  66810. this.L2_2 = this.L2_2.scale(scale);
  66811. this.L2_1 = this.L2_1.scale(scale);
  66812. this.L20 = this.L20.scale(scale);
  66813. this.L21 = this.L21.scale(scale);
  66814. this.L22 = this.L22.scale(scale);
  66815. };
  66816. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  66817. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  66818. //
  66819. // E_lm = A_l * L_lm
  66820. //
  66821. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  66822. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  66823. // the scaling factors are given in equation 9.
  66824. // Constant (Band 0)
  66825. this.L00 = this.L00.scale(3.141593);
  66826. // Linear (Band 1)
  66827. this.L1_1 = this.L1_1.scale(2.094395);
  66828. this.L10 = this.L10.scale(2.094395);
  66829. this.L11 = this.L11.scale(2.094395);
  66830. // Quadratic (Band 2)
  66831. this.L2_2 = this.L2_2.scale(0.785398);
  66832. this.L2_1 = this.L2_1.scale(0.785398);
  66833. this.L20 = this.L20.scale(0.785398);
  66834. this.L21 = this.L21.scale(0.785398);
  66835. this.L22 = this.L22.scale(0.785398);
  66836. };
  66837. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  66838. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  66839. // L = (1/pi) * E * rho
  66840. //
  66841. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  66842. this.scale(1.0 / Math.PI);
  66843. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  66844. // (The pixel shader must apply albedo after texture fetches, etc).
  66845. };
  66846. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  66847. var result = new SphericalHarmonics();
  66848. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  66849. result.L1_1 = polynomial.y.scale(0.977204);
  66850. result.L10 = polynomial.z.scale(0.977204);
  66851. result.L11 = polynomial.x.scale(0.977204);
  66852. result.L2_2 = polynomial.xy.scale(1.16538);
  66853. result.L2_1 = polynomial.yz.scale(1.16538);
  66854. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  66855. result.L21 = polynomial.zx.scale(1.16538);
  66856. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  66857. result.scale(Math.PI);
  66858. return result;
  66859. };
  66860. return SphericalHarmonics;
  66861. }());
  66862. BABYLON.SphericalHarmonics = SphericalHarmonics;
  66863. })(BABYLON || (BABYLON = {}));
  66864. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  66865. var BABYLON;
  66866. (function (BABYLON) {
  66867. var FileFaceOrientation = /** @class */ (function () {
  66868. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  66869. this.name = name;
  66870. this.worldAxisForNormal = worldAxisForNormal;
  66871. this.worldAxisForFileX = worldAxisForFileX;
  66872. this.worldAxisForFileY = worldAxisForFileY;
  66873. }
  66874. return FileFaceOrientation;
  66875. }());
  66876. ;
  66877. /**
  66878. * Helper class dealing with the extraction of spherical polynomial dataArray
  66879. * from a cube map.
  66880. */
  66881. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  66882. function CubeMapToSphericalPolynomialTools() {
  66883. }
  66884. /**
  66885. * Converts a texture to the according Spherical Polynomial data.
  66886. * This extracts the first 3 orders only as they are the only one used in the lighting.
  66887. *
  66888. * @param texture The texture to extract the information from.
  66889. * @return The Spherical Polynomial data.
  66890. */
  66891. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  66892. if (!texture.isCube) {
  66893. // Only supports cube Textures currently.
  66894. return null;
  66895. }
  66896. var size = texture.getSize().width;
  66897. var right = texture.readPixels(0);
  66898. var left = texture.readPixels(1);
  66899. var up;
  66900. var down;
  66901. if (texture.isRenderTarget) {
  66902. up = texture.readPixels(3);
  66903. down = texture.readPixels(2);
  66904. }
  66905. else {
  66906. up = texture.readPixels(2);
  66907. down = texture.readPixels(3);
  66908. }
  66909. var front = texture.readPixels(4);
  66910. var back = texture.readPixels(5);
  66911. var gammaSpace = texture.gammaSpace;
  66912. // Always read as RGBA.
  66913. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  66914. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66915. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66916. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66917. }
  66918. var cubeInfo = {
  66919. size: size,
  66920. right: right,
  66921. left: left,
  66922. up: up,
  66923. down: down,
  66924. front: front,
  66925. back: back,
  66926. format: format,
  66927. type: type,
  66928. gammaSpace: gammaSpace,
  66929. };
  66930. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  66931. };
  66932. /**
  66933. * Converts a cubemap to the according Spherical Polynomial data.
  66934. * This extracts the first 3 orders only as they are the only one used in the lighting.
  66935. *
  66936. * @param cubeInfo The Cube map to extract the information from.
  66937. * @return The Spherical Polynomial data.
  66938. */
  66939. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  66940. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  66941. var totalSolidAngle = 0.0;
  66942. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  66943. var du = 2.0 / cubeInfo.size;
  66944. var dv = du;
  66945. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  66946. var minUV = du * 0.5 - 1.0;
  66947. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  66948. var fileFace = this.FileFaces[faceIndex];
  66949. var dataArray = cubeInfo[fileFace.name];
  66950. var v = minUV;
  66951. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  66952. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  66953. // Because SP is still linear, so summation is fine in that basis.
  66954. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  66955. for (var y = 0; y < cubeInfo.size; y++) {
  66956. var u = minUV;
  66957. for (var x = 0; x < cubeInfo.size; x++) {
  66958. // World direction (not normalised)
  66959. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  66960. worldDirection.normalize();
  66961. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  66962. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  66963. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  66964. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  66965. // Handle Integer types.
  66966. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66967. r /= 255;
  66968. g /= 255;
  66969. b /= 255;
  66970. }
  66971. // Handle Gamma space textures.
  66972. if (cubeInfo.gammaSpace) {
  66973. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  66974. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  66975. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  66976. }
  66977. var color = new BABYLON.Color3(r, g, b);
  66978. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  66979. totalSolidAngle += deltaSolidAngle;
  66980. u += du;
  66981. }
  66982. v += dv;
  66983. }
  66984. }
  66985. // Solid angle for entire sphere is 4*pi
  66986. var sphereSolidAngle = 4.0 * Math.PI;
  66987. // Adjust the solid angle to allow for how many faces we processed.
  66988. var facesProcessed = 6.0;
  66989. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  66990. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  66991. // This is needed because the numerical integration over the cube uses a
  66992. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  66993. // and also to compensate for accumulative error due to float precision in the summation.
  66994. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  66995. sphericalHarmonics.scale(correctionFactor);
  66996. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  66997. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  66998. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  66999. };
  67000. CubeMapToSphericalPolynomialTools.FileFaces = [
  67001. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67002. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67003. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67004. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67005. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67006. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67007. ];
  67008. return CubeMapToSphericalPolynomialTools;
  67009. }());
  67010. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67011. })(BABYLON || (BABYLON = {}));
  67012. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67013. var BABYLON;
  67014. (function (BABYLON) {
  67015. /**
  67016. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67017. */
  67018. var PanoramaToCubeMapTools = /** @class */ (function () {
  67019. function PanoramaToCubeMapTools() {
  67020. }
  67021. /**
  67022. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67023. *
  67024. * @param float32Array The source data.
  67025. * @param inputWidth The width of the input panorama.
  67026. * @param inputhHeight The height of the input panorama.
  67027. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67028. * @return The cubemap data
  67029. */
  67030. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67031. if (!float32Array) {
  67032. throw "ConvertPanoramaToCubemap: input cannot be null";
  67033. }
  67034. if (float32Array.length != inputWidth * inputHeight * 3) {
  67035. throw "ConvertPanoramaToCubemap: input size is wrong";
  67036. }
  67037. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67038. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67039. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67040. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67041. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67042. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67043. return {
  67044. front: textureFront,
  67045. back: textureBack,
  67046. left: textureLeft,
  67047. right: textureRight,
  67048. up: textureUp,
  67049. down: textureDown,
  67050. size: size,
  67051. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67052. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67053. gammaSpace: false,
  67054. };
  67055. };
  67056. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67057. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67058. var textureArray = new Float32Array(buffer);
  67059. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67060. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67061. var dy = 1 / texSize;
  67062. var fy = 0;
  67063. for (var y = 0; y < texSize; y++) {
  67064. var xv1 = faceData[0];
  67065. var xv2 = faceData[2];
  67066. for (var x = 0; x < texSize; x++) {
  67067. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67068. v.normalize();
  67069. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67070. // 3 channels per pixels
  67071. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67072. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67073. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67074. xv1 = xv1.add(rotDX1);
  67075. xv2 = xv2.add(rotDX2);
  67076. }
  67077. fy += dy;
  67078. }
  67079. return textureArray;
  67080. };
  67081. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67082. var theta = Math.atan2(vDir.z, vDir.x);
  67083. var phi = Math.acos(vDir.y);
  67084. while (theta < -Math.PI)
  67085. theta += 2 * Math.PI;
  67086. while (theta > Math.PI)
  67087. theta -= 2 * Math.PI;
  67088. var dx = theta / Math.PI;
  67089. var dy = phi / Math.PI;
  67090. // recenter.
  67091. dx = dx * 0.5 + 0.5;
  67092. var px = Math.round(dx * inputWidth);
  67093. if (px < 0)
  67094. px = 0;
  67095. else if (px >= inputWidth)
  67096. px = inputWidth - 1;
  67097. var py = Math.round(dy * inputHeight);
  67098. if (py < 0)
  67099. py = 0;
  67100. else if (py >= inputHeight)
  67101. py = inputHeight - 1;
  67102. var inputY = (inputHeight - py - 1);
  67103. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67104. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67105. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67106. return {
  67107. r: r,
  67108. g: g,
  67109. b: b
  67110. };
  67111. };
  67112. PanoramaToCubeMapTools.FACE_FRONT = [
  67113. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67114. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67115. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67116. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67117. ];
  67118. PanoramaToCubeMapTools.FACE_BACK = [
  67119. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67120. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67121. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67122. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67123. ];
  67124. PanoramaToCubeMapTools.FACE_RIGHT = [
  67125. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67126. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67127. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67128. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67129. ];
  67130. PanoramaToCubeMapTools.FACE_LEFT = [
  67131. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67132. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67133. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67134. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67135. ];
  67136. PanoramaToCubeMapTools.FACE_DOWN = [
  67137. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67138. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67139. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67140. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67141. ];
  67142. PanoramaToCubeMapTools.FACE_UP = [
  67143. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67144. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67145. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67146. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67147. ];
  67148. return PanoramaToCubeMapTools;
  67149. }());
  67150. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67151. })(BABYLON || (BABYLON = {}));
  67152. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67153. var BABYLON;
  67154. (function (BABYLON) {
  67155. ;
  67156. /**
  67157. * This groups tools to convert HDR texture to native colors array.
  67158. */
  67159. var HDRTools = /** @class */ (function () {
  67160. function HDRTools() {
  67161. }
  67162. HDRTools.Ldexp = function (mantissa, exponent) {
  67163. if (exponent > 1023) {
  67164. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67165. }
  67166. if (exponent < -1074) {
  67167. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67168. }
  67169. return mantissa * Math.pow(2, exponent);
  67170. };
  67171. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67172. if (exponent > 0) {
  67173. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67174. float32array[index + 0] = red * exponent;
  67175. float32array[index + 1] = green * exponent;
  67176. float32array[index + 2] = blue * exponent;
  67177. }
  67178. else {
  67179. float32array[index + 0] = 0;
  67180. float32array[index + 1] = 0;
  67181. float32array[index + 2] = 0;
  67182. }
  67183. };
  67184. HDRTools.readStringLine = function (uint8array, startIndex) {
  67185. var line = "";
  67186. var character = "";
  67187. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67188. character = String.fromCharCode(uint8array[i]);
  67189. if (character == "\n") {
  67190. break;
  67191. }
  67192. line += character;
  67193. }
  67194. return line;
  67195. };
  67196. /**
  67197. * Reads header information from an RGBE texture stored in a native array.
  67198. * More information on this format are available here:
  67199. * https://en.wikipedia.org/wiki/RGBE_image_format
  67200. *
  67201. * @param uint8array The binary file stored in native array.
  67202. * @return The header information.
  67203. */
  67204. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67205. var height = 0;
  67206. var width = 0;
  67207. var line = this.readStringLine(uint8array, 0);
  67208. if (line[0] != '#' || line[1] != '?') {
  67209. throw "Bad HDR Format.";
  67210. }
  67211. var endOfHeader = false;
  67212. var findFormat = false;
  67213. var lineIndex = 0;
  67214. do {
  67215. lineIndex += (line.length + 1);
  67216. line = this.readStringLine(uint8array, lineIndex);
  67217. if (line == "FORMAT=32-bit_rle_rgbe") {
  67218. findFormat = true;
  67219. }
  67220. else if (line.length == 0) {
  67221. endOfHeader = true;
  67222. }
  67223. } while (!endOfHeader);
  67224. if (!findFormat) {
  67225. throw "HDR Bad header format, unsupported FORMAT";
  67226. }
  67227. lineIndex += (line.length + 1);
  67228. line = this.readStringLine(uint8array, lineIndex);
  67229. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67230. var match = sizeRegexp.exec(line);
  67231. // TODO. Support +Y and -X if needed.
  67232. if (!match || match.length < 3) {
  67233. throw "HDR Bad header format, no size";
  67234. }
  67235. width = parseInt(match[2]);
  67236. height = parseInt(match[1]);
  67237. if (width < 8 || width > 0x7fff) {
  67238. throw "HDR Bad header format, unsupported size";
  67239. }
  67240. lineIndex += (line.length + 1);
  67241. return {
  67242. height: height,
  67243. width: width,
  67244. dataPosition: lineIndex
  67245. };
  67246. };
  67247. /**
  67248. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  67249. * This RGBE texture needs to store the information as a panorama.
  67250. *
  67251. * More information on this format are available here:
  67252. * https://en.wikipedia.org/wiki/RGBE_image_format
  67253. *
  67254. * @param buffer The binary file stored in an array buffer.
  67255. * @param size The expected size of the extracted cubemap.
  67256. * @return The Cube Map information.
  67257. */
  67258. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  67259. var uint8array = new Uint8Array(buffer);
  67260. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  67261. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67262. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  67263. return cubeMapData;
  67264. };
  67265. /**
  67266. * Returns the pixels data extracted from an RGBE texture.
  67267. * This pixels will be stored left to right up to down in the R G B order in one array.
  67268. *
  67269. * More information on this format are available here:
  67270. * https://en.wikipedia.org/wiki/RGBE_image_format
  67271. *
  67272. * @param uint8array The binary file stored in an array buffer.
  67273. * @param hdrInfo The header information of the file.
  67274. * @return The pixels data in RGB right to left up to down order.
  67275. */
  67276. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  67277. // Keep for multi format supports.
  67278. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67279. };
  67280. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  67281. var num_scanlines = hdrInfo.height;
  67282. var scanline_width = hdrInfo.width;
  67283. var a, b, c, d, count;
  67284. var dataIndex = hdrInfo.dataPosition;
  67285. var index = 0, endIndex = 0, i = 0;
  67286. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  67287. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  67288. // 3 channels of 4 bytes per pixel in float.
  67289. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  67290. var resultArray = new Float32Array(resultBuffer);
  67291. // read in each successive scanline
  67292. while (num_scanlines > 0) {
  67293. a = uint8array[dataIndex++];
  67294. b = uint8array[dataIndex++];
  67295. c = uint8array[dataIndex++];
  67296. d = uint8array[dataIndex++];
  67297. if (a != 2 || b != 2 || (c & 0x80)) {
  67298. // this file is not run length encoded
  67299. throw "HDR Bad header format, not RLE";
  67300. }
  67301. if (((c << 8) | d) != scanline_width) {
  67302. throw "HDR Bad header format, wrong scan line width";
  67303. }
  67304. index = 0;
  67305. // read each of the four channels for the scanline into the buffer
  67306. for (i = 0; i < 4; i++) {
  67307. endIndex = (i + 1) * scanline_width;
  67308. while (index < endIndex) {
  67309. a = uint8array[dataIndex++];
  67310. b = uint8array[dataIndex++];
  67311. if (a > 128) {
  67312. // a run of the same value
  67313. count = a - 128;
  67314. if ((count == 0) || (count > endIndex - index)) {
  67315. throw "HDR Bad Format, bad scanline data (run)";
  67316. }
  67317. while (count-- > 0) {
  67318. scanLineArray[index++] = b;
  67319. }
  67320. }
  67321. else {
  67322. // a non-run
  67323. count = a;
  67324. if ((count == 0) || (count > endIndex - index)) {
  67325. throw "HDR Bad Format, bad scanline data (non-run)";
  67326. }
  67327. scanLineArray[index++] = b;
  67328. if (--count > 0) {
  67329. for (var j = 0; j < count; j++) {
  67330. scanLineArray[index++] = uint8array[dataIndex++];
  67331. }
  67332. }
  67333. }
  67334. }
  67335. }
  67336. // now convert data from buffer into floats
  67337. for (i = 0; i < scanline_width; i++) {
  67338. a = scanLineArray[i];
  67339. b = scanLineArray[i + scanline_width];
  67340. c = scanLineArray[i + 2 * scanline_width];
  67341. d = scanLineArray[i + 3 * scanline_width];
  67342. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  67343. }
  67344. num_scanlines--;
  67345. }
  67346. return resultArray;
  67347. };
  67348. return HDRTools;
  67349. }());
  67350. BABYLON.HDRTools = HDRTools;
  67351. })(BABYLON || (BABYLON = {}));
  67352. //# sourceMappingURL=babylon.hdr.js.map
  67353. var BABYLON;
  67354. (function (BABYLON) {
  67355. /**
  67356. * This represents a texture coming from an HDR input.
  67357. *
  67358. * The only supported format is currently panorama picture stored in RGBE format.
  67359. * Example of such files can be found on HDRLib: http://hdrlib.com/
  67360. */
  67361. var HDRCubeTexture = /** @class */ (function (_super) {
  67362. __extends(HDRCubeTexture, _super);
  67363. /**
  67364. * Instantiates an HDRTexture from the following parameters.
  67365. *
  67366. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  67367. * @param scene The scene the texture will be used in
  67368. * @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.
  67369. * @param noMipmap Forces to not generate the mipmap if true
  67370. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  67371. * @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)
  67372. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  67373. */
  67374. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  67375. if (noMipmap === void 0) { noMipmap = false; }
  67376. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67377. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67378. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67379. if (onLoad === void 0) { onLoad = null; }
  67380. if (onError === void 0) { onError = null; }
  67381. var _this = _super.call(this, scene) || this;
  67382. _this._useInGammaSpace = false;
  67383. _this._generateHarmonics = true;
  67384. _this._isBABYLONPreprocessed = false;
  67385. _this._onLoad = null;
  67386. _this._onError = null;
  67387. /**
  67388. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  67389. */
  67390. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67391. /**
  67392. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  67393. * This is usefull at run time to apply the good shader.
  67394. */
  67395. _this.isPMREM = false;
  67396. _this._isBlocking = true;
  67397. if (!url) {
  67398. return _this;
  67399. }
  67400. _this.name = url;
  67401. _this.url = url;
  67402. _this.hasAlpha = false;
  67403. _this.isCube = true;
  67404. _this._textureMatrix = BABYLON.Matrix.Identity();
  67405. _this._onLoad = onLoad;
  67406. _this._onError = onError;
  67407. _this.gammaSpace = false;
  67408. var caps = scene.getEngine().getCaps();
  67409. if (size) {
  67410. _this._isBABYLONPreprocessed = false;
  67411. _this._noMipmap = noMipmap;
  67412. _this._size = size;
  67413. _this._useInGammaSpace = useInGammaSpace;
  67414. _this._usePMREMGenerator = usePMREMGenerator &&
  67415. caps.textureLOD &&
  67416. caps.textureFloat &&
  67417. !_this._useInGammaSpace;
  67418. }
  67419. else {
  67420. _this._isBABYLONPreprocessed = true;
  67421. _this._noMipmap = false;
  67422. _this._useInGammaSpace = false;
  67423. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  67424. !_this._useInGammaSpace;
  67425. }
  67426. _this.isPMREM = _this._usePMREMGenerator;
  67427. _this._texture = _this._getFromCache(url, _this._noMipmap);
  67428. if (!_this._texture) {
  67429. if (!scene.useDelayedTextureLoading) {
  67430. _this.loadTexture();
  67431. }
  67432. else {
  67433. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67434. }
  67435. }
  67436. return _this;
  67437. }
  67438. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  67439. /**
  67440. * Gets wether or not the texture is blocking during loading.
  67441. */
  67442. get: function () {
  67443. return this._isBlocking;
  67444. },
  67445. /**
  67446. * Sets wether or not the texture is blocking during loading.
  67447. */
  67448. set: function (value) {
  67449. this._isBlocking = value;
  67450. },
  67451. enumerable: true,
  67452. configurable: true
  67453. });
  67454. /**
  67455. * Occurs when the file is a preprocessed .babylon.hdr file.
  67456. */
  67457. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  67458. var _this = this;
  67459. var mipLevels = 0;
  67460. var floatArrayView = null;
  67461. var scene = this.getScene();
  67462. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  67463. var mips = new Array();
  67464. if (!floatArrayView) {
  67465. return mips;
  67466. }
  67467. var startIndex = 30;
  67468. for (var level = 0; level < mipLevels; level++) {
  67469. mips.push([]);
  67470. // Fill each pixel of the mip level.
  67471. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  67472. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67473. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  67474. mips[level].push(faceData);
  67475. startIndex += faceSize;
  67476. }
  67477. }
  67478. return mips;
  67479. } : null;
  67480. var callback = function (buffer) {
  67481. var scene = _this.getScene();
  67482. if (!scene) {
  67483. return null;
  67484. }
  67485. // Create Native Array Views
  67486. var intArrayView = new Int32Array(buffer);
  67487. floatArrayView = new Float32Array(buffer);
  67488. // Fill header.
  67489. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  67490. _this._size = intArrayView[1]; // CubeMap max mip face size.
  67491. // Update Texture Information.
  67492. if (!_this._texture) {
  67493. return null;
  67494. }
  67495. _this._texture.updateSize(_this._size, _this._size);
  67496. // Fill polynomial information.
  67497. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  67498. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  67499. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  67500. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  67501. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  67502. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  67503. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  67504. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  67505. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  67506. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  67507. _this.sphericalPolynomial = sphericalPolynomial;
  67508. // Fill pixel data.
  67509. mipLevels = intArrayView[29]; // Number of mip levels.
  67510. var startIndex = 30;
  67511. var data = [];
  67512. var faceSize = Math.pow(_this._size, 2) * 3;
  67513. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67514. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  67515. startIndex += faceSize;
  67516. }
  67517. var results = [];
  67518. var byteArray = null;
  67519. // Push each faces.
  67520. for (var k = 0; k < 6; k++) {
  67521. var dataFace = null;
  67522. // To be deprecated.
  67523. if (version === 1) {
  67524. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  67525. dataFace = data[j];
  67526. }
  67527. // If special cases.
  67528. if (!mipmapGenerator && dataFace) {
  67529. if (!scene.getEngine().getCaps().textureFloat) {
  67530. // 3 channels of 1 bytes per pixel in bytes.
  67531. var byteBuffer = new ArrayBuffer(faceSize);
  67532. byteArray = new Uint8Array(byteBuffer);
  67533. }
  67534. for (var i = 0; i < _this._size * _this._size; i++) {
  67535. // Put in gamma space if requested.
  67536. if (_this._useInGammaSpace) {
  67537. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67538. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67539. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67540. }
  67541. // Convert to int texture for fallback.
  67542. if (byteArray) {
  67543. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67544. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67545. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67546. // May use luminance instead if the result is not accurate.
  67547. var max = Math.max(Math.max(r, g), b);
  67548. if (max > 255) {
  67549. var scale = 255 / max;
  67550. r *= scale;
  67551. g *= scale;
  67552. b *= scale;
  67553. }
  67554. byteArray[(i * 3) + 0] = r;
  67555. byteArray[(i * 3) + 1] = g;
  67556. byteArray[(i * 3) + 2] = b;
  67557. }
  67558. }
  67559. }
  67560. // Fill the array accordingly.
  67561. if (byteArray) {
  67562. results.push(byteArray);
  67563. }
  67564. else {
  67565. results.push(dataFace);
  67566. }
  67567. }
  67568. return results;
  67569. };
  67570. if (scene) {
  67571. 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);
  67572. }
  67573. };
  67574. /**
  67575. * Occurs when the file is raw .hdr file.
  67576. */
  67577. HDRCubeTexture.prototype.loadHDRTexture = function () {
  67578. var _this = this;
  67579. var callback = function (buffer) {
  67580. var scene = _this.getScene();
  67581. if (!scene) {
  67582. return null;
  67583. }
  67584. // Extract the raw linear data.
  67585. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  67586. // Generate harmonics if needed.
  67587. if (_this._generateHarmonics) {
  67588. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  67589. _this.sphericalPolynomial = sphericalPolynomial;
  67590. }
  67591. var results = [];
  67592. var byteArray = null;
  67593. // Push each faces.
  67594. for (var j = 0; j < 6; j++) {
  67595. // Create uintarray fallback.
  67596. if (!scene.getEngine().getCaps().textureFloat) {
  67597. // 3 channels of 1 bytes per pixel in bytes.
  67598. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  67599. byteArray = new Uint8Array(byteBuffer);
  67600. }
  67601. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  67602. // If special cases.
  67603. if (_this._useInGammaSpace || byteArray) {
  67604. for (var i = 0; i < _this._size * _this._size; i++) {
  67605. // Put in gamma space if requested.
  67606. if (_this._useInGammaSpace) {
  67607. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67608. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67609. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67610. }
  67611. // Convert to int texture for fallback.
  67612. if (byteArray) {
  67613. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67614. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67615. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67616. // May use luminance instead if the result is not accurate.
  67617. var max = Math.max(Math.max(r, g), b);
  67618. if (max > 255) {
  67619. var scale = 255 / max;
  67620. r *= scale;
  67621. g *= scale;
  67622. b *= scale;
  67623. }
  67624. byteArray[(i * 3) + 0] = r;
  67625. byteArray[(i * 3) + 1] = g;
  67626. byteArray[(i * 3) + 2] = b;
  67627. }
  67628. }
  67629. }
  67630. if (byteArray) {
  67631. results.push(byteArray);
  67632. }
  67633. else {
  67634. results.push(dataFace);
  67635. }
  67636. }
  67637. return results;
  67638. };
  67639. var mipmapGenerator = null;
  67640. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  67641. // if (!this._noMipmap &&
  67642. // this._usePMREMGenerator) {
  67643. // mipmapGenerator = (data: ArrayBufferView[]) => {
  67644. // // Custom setup of the generator matching with the PBR shader values.
  67645. // var generator = new BABYLON.PMREMGenerator(data,
  67646. // this._size,
  67647. // this._size,
  67648. // 0,
  67649. // 3,
  67650. // this.getScene().getEngine().getCaps().textureFloat,
  67651. // 2048,
  67652. // 0.25,
  67653. // false,
  67654. // true);
  67655. // return generator.filterCubeMap();
  67656. // };
  67657. // }
  67658. var scene = this.getScene();
  67659. if (scene) {
  67660. 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);
  67661. }
  67662. };
  67663. /**
  67664. * Starts the loading process of the texture.
  67665. */
  67666. HDRCubeTexture.prototype.loadTexture = function () {
  67667. if (this._isBABYLONPreprocessed) {
  67668. this.loadBabylonTexture();
  67669. }
  67670. else {
  67671. this.loadHDRTexture();
  67672. }
  67673. };
  67674. HDRCubeTexture.prototype.clone = function () {
  67675. var scene = this.getScene();
  67676. if (!scene) {
  67677. return this;
  67678. }
  67679. var size = (this._isBABYLONPreprocessed ? null : this._size);
  67680. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  67681. // Base texture
  67682. newTexture.level = this.level;
  67683. newTexture.wrapU = this.wrapU;
  67684. newTexture.wrapV = this.wrapV;
  67685. newTexture.coordinatesIndex = this.coordinatesIndex;
  67686. newTexture.coordinatesMode = this.coordinatesMode;
  67687. return newTexture;
  67688. };
  67689. // Methods
  67690. HDRCubeTexture.prototype.delayLoad = function () {
  67691. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  67692. return;
  67693. }
  67694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  67695. this._texture = this._getFromCache(this.url, this._noMipmap);
  67696. if (!this._texture) {
  67697. this.loadTexture();
  67698. }
  67699. };
  67700. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  67701. return this._textureMatrix;
  67702. };
  67703. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  67704. this._textureMatrix = value;
  67705. };
  67706. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  67707. var texture = null;
  67708. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  67709. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  67710. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  67711. texture.name = parsedTexture.name;
  67712. texture.hasAlpha = parsedTexture.hasAlpha;
  67713. texture.level = parsedTexture.level;
  67714. texture.coordinatesMode = parsedTexture.coordinatesMode;
  67715. texture.isBlocking = parsedTexture.isBlocking;
  67716. }
  67717. return texture;
  67718. };
  67719. HDRCubeTexture.prototype.serialize = function () {
  67720. if (!this.name) {
  67721. return null;
  67722. }
  67723. var serializationObject = {};
  67724. serializationObject.name = this.name;
  67725. serializationObject.hasAlpha = this.hasAlpha;
  67726. serializationObject.isCube = true;
  67727. serializationObject.level = this.level;
  67728. serializationObject.size = this._size;
  67729. serializationObject.coordinatesMode = this.coordinatesMode;
  67730. serializationObject.useInGammaSpace = this._useInGammaSpace;
  67731. serializationObject.generateHarmonics = this._generateHarmonics;
  67732. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  67733. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  67734. serializationObject.customType = "BABYLON.HDRCubeTexture";
  67735. serializationObject.noMipmap = this._noMipmap;
  67736. serializationObject.isBlocking = this._isBlocking;
  67737. return serializationObject;
  67738. };
  67739. /**
  67740. * Saves as a file the data contained in the texture in a binary format.
  67741. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67742. * as the spherical used in the lighting.
  67743. * @param url The HDR file url.
  67744. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67745. * @param onError Method called if any error happens during download.
  67746. * @return The packed binary data.
  67747. */
  67748. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  67749. if (onError === void 0) { onError = null; }
  67750. var callback = function (buffer) {
  67751. var data = new Blob([buffer], { type: 'application/octet-stream' });
  67752. // Returns a URL you can use as a href.
  67753. var objUrl = window.URL.createObjectURL(data);
  67754. // Simulates a link to it and click to dowload.
  67755. var a = document.createElement("a");
  67756. document.body.appendChild(a);
  67757. a.style.display = "none";
  67758. a.href = objUrl;
  67759. a.download = "envmap.babylon.hdr";
  67760. a.click();
  67761. };
  67762. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  67763. };
  67764. /**
  67765. * Serializes the data contained in the texture in a binary format.
  67766. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  67767. * as the spherical used in the lighting.
  67768. * @param url The HDR file url.
  67769. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  67770. * @param onError Method called if any error happens during download.
  67771. * @return The packed binary data.
  67772. */
  67773. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  67774. if (onError === void 0) { onError = null; }
  67775. // Needs the url tho create the texture.
  67776. if (!url) {
  67777. return;
  67778. }
  67779. // Check Power of two size.
  67780. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  67781. return;
  67782. }
  67783. // Coming Back in 3.x.
  67784. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  67785. };
  67786. HDRCubeTexture._facesMapping = [
  67787. "right",
  67788. "left",
  67789. "up",
  67790. "down",
  67791. "front",
  67792. "back"
  67793. ];
  67794. return HDRCubeTexture;
  67795. }(BABYLON.BaseTexture));
  67796. BABYLON.HDRCubeTexture = HDRCubeTexture;
  67797. })(BABYLON || (BABYLON = {}));
  67798. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  67799. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  67800. // Huge respect for a such great lib.
  67801. // Earcut license:
  67802. // Copyright (c) 2016, Mapbox
  67803. //
  67804. // Permission to use, copy, modify, and/or distribute this software for any purpose
  67805. // with or without fee is hereby granted, provided that the above copyright notice
  67806. // and this permission notice appear in all copies.
  67807. //
  67808. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  67809. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  67810. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  67811. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  67812. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  67813. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  67814. // THIS SOFTWARE.
  67815. var Earcut;
  67816. (function (Earcut) {
  67817. /**
  67818. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  67819. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  67820. * @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).
  67821. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  67822. */
  67823. function earcut(data, holeIndices, dim) {
  67824. dim = dim || 2;
  67825. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  67826. if (!outerNode)
  67827. return triangles;
  67828. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  67829. if (hasHoles)
  67830. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  67831. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  67832. if (data.length > 80 * dim) {
  67833. minX = maxX = data[0];
  67834. minY = maxY = data[1];
  67835. for (var i = dim; i < outerLen; i += dim) {
  67836. x = data[i];
  67837. y = data[i + 1];
  67838. if (x < minX)
  67839. minX = x;
  67840. if (y < minY)
  67841. minY = y;
  67842. if (x > maxX)
  67843. maxX = x;
  67844. if (y > maxY)
  67845. maxY = y;
  67846. }
  67847. // minX, minY and size are later used to transform coords into integers for z-order calculation
  67848. size = Math.max(maxX - minX, maxY - minY);
  67849. }
  67850. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  67851. return triangles;
  67852. }
  67853. Earcut.earcut = earcut;
  67854. var Node = /** @class */ (function () {
  67855. function Node(i, x, y) {
  67856. this.i = i;
  67857. this.x = x;
  67858. this.y = y;
  67859. this.prev = null;
  67860. this.next = null;
  67861. this.z = null;
  67862. this.prevZ = null;
  67863. this.nextZ = null;
  67864. this.steiner = false;
  67865. }
  67866. return Node;
  67867. }());
  67868. // create a circular doubly linked list from polygon points in the specified winding order
  67869. function linkedList(data, start, end, dim, clockwise) {
  67870. var i, last = null;
  67871. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  67872. for (i = start; i < end; i += dim)
  67873. last = insertNode(i, data[i], data[i + 1], last);
  67874. }
  67875. else {
  67876. for (i = end - dim; i >= start; i -= dim)
  67877. last = insertNode(i, data[i], data[i + 1], last);
  67878. }
  67879. if (last && equals(last, last.next)) {
  67880. removeNode(last);
  67881. last = last.next;
  67882. }
  67883. return last;
  67884. }
  67885. // eliminate colinear or duplicate points
  67886. function filterPoints(start, end) {
  67887. if (!start)
  67888. return start;
  67889. if (!end)
  67890. end = start;
  67891. var p = start, again;
  67892. do {
  67893. again = false;
  67894. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  67895. removeNode(p);
  67896. p = end = p.prev;
  67897. if (p === p.next)
  67898. return undefined;
  67899. again = true;
  67900. }
  67901. else {
  67902. p = p.next;
  67903. }
  67904. } while (again || p !== end);
  67905. return end;
  67906. }
  67907. // main ear slicing loop which triangulates a polygon (given as a linked list)
  67908. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  67909. if (!ear)
  67910. return;
  67911. // interlink polygon nodes in z-order
  67912. if (!pass && size)
  67913. indexCurve(ear, minX, minY, size);
  67914. var stop = ear, prev, next;
  67915. // iterate through ears, slicing them one by one
  67916. while (ear.prev !== ear.next) {
  67917. prev = ear.prev;
  67918. next = ear.next;
  67919. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  67920. // cut off the triangle
  67921. triangles.push(prev.i / dim);
  67922. triangles.push(ear.i / dim);
  67923. triangles.push(next.i / dim);
  67924. removeNode(ear);
  67925. // skipping the next vertice leads to less sliver triangles
  67926. ear = next.next;
  67927. stop = next.next;
  67928. continue;
  67929. }
  67930. ear = next;
  67931. // if we looped through the whole remaining polygon and can't find any more ears
  67932. if (ear === stop) {
  67933. // try filtering points and slicing again
  67934. if (!pass) {
  67935. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  67936. // if this didn't work, try curing all small self-intersections locally
  67937. }
  67938. else if (pass === 1) {
  67939. ear = cureLocalIntersections(ear, triangles, dim);
  67940. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  67941. // as a last resort, try splitting the remaining polygon into two
  67942. }
  67943. else if (pass === 2) {
  67944. splitEarcut(ear, triangles, dim, minX, minY, size);
  67945. }
  67946. break;
  67947. }
  67948. }
  67949. }
  67950. // check whether a polygon node forms a valid ear with adjacent nodes
  67951. function isEar(ear) {
  67952. var a = ear.prev, b = ear, c = ear.next;
  67953. if (area(a, b, c) >= 0)
  67954. return false; // reflex, can't be an ear
  67955. // now make sure we don't have other points inside the potential ear
  67956. var p = ear.next.next;
  67957. while (p !== ear.prev) {
  67958. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  67959. area(p.prev, p, p.next) >= 0)
  67960. return false;
  67961. p = p.next;
  67962. }
  67963. return true;
  67964. }
  67965. function isEarHashed(ear, minX, minY, size) {
  67966. var a = ear.prev, b = ear, c = ear.next;
  67967. if (area(a, b, c) >= 0)
  67968. return false; // reflex, can't be an ear
  67969. // triangle bbox; min & max are calculated like this for speed
  67970. 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);
  67971. // z-order range for the current triangle bbox;
  67972. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  67973. // first look for points inside the triangle in increasing z-order
  67974. var p = ear.nextZ;
  67975. while (p && p.z <= maxZ) {
  67976. if (p !== ear.prev &&
  67977. p !== ear.next &&
  67978. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  67979. area(p.prev, p, p.next) >= 0)
  67980. return false;
  67981. p = p.nextZ;
  67982. }
  67983. // then look for points in decreasing z-order
  67984. p = ear.prevZ;
  67985. while (p && p.z >= minZ) {
  67986. if (p !== ear.prev &&
  67987. p !== ear.next &&
  67988. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  67989. area(p.prev, p, p.next) >= 0)
  67990. return false;
  67991. p = p.prevZ;
  67992. }
  67993. return true;
  67994. }
  67995. // go through all polygon nodes and cure small local self-intersections
  67996. function cureLocalIntersections(start, triangles, dim) {
  67997. var p = start;
  67998. do {
  67999. var a = p.prev, b = p.next.next;
  68000. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68001. triangles.push(a.i / dim);
  68002. triangles.push(p.i / dim);
  68003. triangles.push(b.i / dim);
  68004. // remove two nodes involved
  68005. removeNode(p);
  68006. removeNode(p.next);
  68007. p = start = b;
  68008. }
  68009. p = p.next;
  68010. } while (p !== start);
  68011. return p;
  68012. }
  68013. // try splitting polygon into two and triangulate them independently
  68014. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68015. // look for a valid diagonal that divides the polygon into two
  68016. var a = start;
  68017. do {
  68018. var b = a.next.next;
  68019. while (b !== a.prev) {
  68020. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68021. // split the polygon in two by the diagonal
  68022. var c = splitPolygon(a, b);
  68023. // filter colinear points around the cuts
  68024. a = filterPoints(a, a.next);
  68025. c = filterPoints(c, c.next);
  68026. // run earcut on each half
  68027. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68028. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68029. return;
  68030. }
  68031. b = b.next;
  68032. }
  68033. a = a.next;
  68034. } while (a !== start);
  68035. }
  68036. // link every hole into the outer loop, producing a single-ring polygon without holes
  68037. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68038. var queue = [], i, len, start, end, list;
  68039. for (i = 0, len = holeIndices.length; i < len; i++) {
  68040. start = holeIndices[i] * dim;
  68041. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68042. list = linkedList(data, start, end, dim, false);
  68043. if (list === list.next)
  68044. list.steiner = true;
  68045. queue.push(getLeftmost(list));
  68046. }
  68047. queue.sort(compareX);
  68048. // process holes from left to right
  68049. for (i = 0; i < queue.length; i++) {
  68050. eliminateHole(queue[i], outerNode);
  68051. outerNode = filterPoints(outerNode, outerNode.next);
  68052. }
  68053. return outerNode;
  68054. }
  68055. function compareX(a, b) {
  68056. return a.x - b.x;
  68057. }
  68058. // find a bridge between vertices that connects hole with an outer ring and and link it
  68059. function eliminateHole(hole, outerNode) {
  68060. outerNode = findHoleBridge(hole, outerNode);
  68061. if (outerNode) {
  68062. var b = splitPolygon(outerNode, hole);
  68063. filterPoints(b, b.next);
  68064. }
  68065. }
  68066. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68067. function findHoleBridge(hole, outerNode) {
  68068. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68069. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68070. // segment's endpoint with lesser x will be potential connection point
  68071. do {
  68072. if (hy <= p.y && hy >= p.next.y) {
  68073. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68074. if (x <= hx && x > qx) {
  68075. qx = x;
  68076. if (x === hx) {
  68077. if (hy === p.y)
  68078. return p;
  68079. if (hy === p.next.y)
  68080. return p.next;
  68081. }
  68082. m = p.x < p.next.x ? p : p.next;
  68083. }
  68084. }
  68085. p = p.next;
  68086. } while (p !== outerNode);
  68087. if (!m)
  68088. return null;
  68089. if (hx === qx)
  68090. return m.prev; // hole touches outer segment; pick lower endpoint
  68091. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68092. // if there are no points found, we have a valid connection;
  68093. // otherwise choose the point of the minimum angle with the ray as connection point
  68094. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68095. p = m.next;
  68096. while (p !== stop) {
  68097. if (hx >= p.x &&
  68098. p.x >= mx &&
  68099. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68100. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68101. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68102. m = p;
  68103. tanMin = tan;
  68104. }
  68105. }
  68106. p = p.next;
  68107. }
  68108. return m;
  68109. }
  68110. // interlink polygon nodes in z-order
  68111. function indexCurve(start, minX, minY, size) {
  68112. var p = start;
  68113. do {
  68114. if (p.z === null)
  68115. p.z = zOrder(p.x, p.y, minX, minY, size);
  68116. p.prevZ = p.prev;
  68117. p.nextZ = p.next;
  68118. p = p.next;
  68119. } while (p !== start);
  68120. p.prevZ.nextZ = null;
  68121. p.prevZ = null;
  68122. sortLinked(p);
  68123. }
  68124. // Simon Tatham's linked list merge sort algorithm
  68125. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68126. function sortLinked(list) {
  68127. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68128. do {
  68129. p = list;
  68130. list = null;
  68131. tail = null;
  68132. numMerges = 0;
  68133. while (p) {
  68134. numMerges++;
  68135. q = p;
  68136. pSize = 0;
  68137. for (i = 0; i < inSize; i++) {
  68138. pSize++;
  68139. q = q.nextZ;
  68140. if (!q)
  68141. break;
  68142. }
  68143. qSize = inSize;
  68144. while (pSize > 0 || (qSize > 0 && q)) {
  68145. if (pSize === 0) {
  68146. e = q;
  68147. q = q.nextZ;
  68148. qSize--;
  68149. }
  68150. else if (qSize === 0 || !q) {
  68151. e = p;
  68152. p = p.nextZ;
  68153. pSize--;
  68154. }
  68155. else if (p.z <= q.z) {
  68156. e = p;
  68157. p = p.nextZ;
  68158. pSize--;
  68159. }
  68160. else {
  68161. e = q;
  68162. q = q.nextZ;
  68163. qSize--;
  68164. }
  68165. if (tail)
  68166. tail.nextZ = e;
  68167. else
  68168. list = e;
  68169. e.prevZ = tail;
  68170. tail = e;
  68171. }
  68172. p = q;
  68173. }
  68174. tail.nextZ = null;
  68175. inSize *= 2;
  68176. } while (numMerges > 1);
  68177. return list;
  68178. }
  68179. // z-order of a point given coords and size of the data bounding box
  68180. function zOrder(x, y, minX, minY, size) {
  68181. // coords are transformed into non-negative 15-bit integer range
  68182. x = 32767 * (x - minX) / size;
  68183. y = 32767 * (y - minY) / size;
  68184. x = (x | (x << 8)) & 0x00FF00FF;
  68185. x = (x | (x << 4)) & 0x0F0F0F0F;
  68186. x = (x | (x << 2)) & 0x33333333;
  68187. x = (x | (x << 1)) & 0x55555555;
  68188. y = (y | (y << 8)) & 0x00FF00FF;
  68189. y = (y | (y << 4)) & 0x0F0F0F0F;
  68190. y = (y | (y << 2)) & 0x33333333;
  68191. y = (y | (y << 1)) & 0x55555555;
  68192. return x | (y << 1);
  68193. }
  68194. // find the leftmost node of a polygon ring
  68195. function getLeftmost(start) {
  68196. var p = start, leftmost = start;
  68197. do {
  68198. if (p.x < leftmost.x)
  68199. leftmost = p;
  68200. p = p.next;
  68201. } while (p !== start);
  68202. return leftmost;
  68203. }
  68204. // check if a point lies within a convex triangle
  68205. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68206. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68207. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68208. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68209. }
  68210. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68211. function isValidDiagonal(a, b) {
  68212. return a.next.i !== b.i &&
  68213. a.prev.i !== b.i &&
  68214. !intersectsPolygon(a, b) &&
  68215. locallyInside(a, b) &&
  68216. locallyInside(b, a) &&
  68217. middleInside(a, b);
  68218. }
  68219. // signed area of a triangle
  68220. function area(p, q, r) {
  68221. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68222. }
  68223. // check if two points are equal
  68224. function equals(p1, p2) {
  68225. return p1.x === p2.x && p1.y === p2.y;
  68226. }
  68227. // check if two segments intersect
  68228. function intersects(p1, q1, p2, q2) {
  68229. if ((equals(p1, q1) && equals(p2, q2)) ||
  68230. (equals(p1, q2) && equals(p2, q1)))
  68231. return true;
  68232. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  68233. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  68234. }
  68235. // check if a polygon diagonal intersects any polygon segments
  68236. function intersectsPolygon(a, b) {
  68237. var p = a;
  68238. do {
  68239. if (p.i !== a.i &&
  68240. p.next.i !== a.i &&
  68241. p.i !== b.i &&
  68242. p.next.i !== b.i &&
  68243. intersects(p, p.next, a, b))
  68244. return true;
  68245. p = p.next;
  68246. } while (p !== a);
  68247. return false;
  68248. }
  68249. // check if a polygon diagonal is locally inside the polygon
  68250. function locallyInside(a, b) {
  68251. return area(a.prev, a, a.next) < 0
  68252. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  68253. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  68254. }
  68255. // check if the middle point of a polygon diagonal is inside the polygon
  68256. function middleInside(a, b) {
  68257. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  68258. do {
  68259. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  68260. inside = !inside;
  68261. p = p.next;
  68262. } while (p !== a);
  68263. return inside;
  68264. }
  68265. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  68266. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  68267. function splitPolygon(a, b) {
  68268. 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;
  68269. a.next = b;
  68270. b.prev = a;
  68271. a2.next = an;
  68272. an.prev = a2;
  68273. b2.next = a2;
  68274. a2.prev = b2;
  68275. bp.next = b2;
  68276. b2.prev = bp;
  68277. return b2;
  68278. }
  68279. // create a node and optionally link it with previous one (in a circular doubly linked list)
  68280. function insertNode(i, x, y, last) {
  68281. var p = new Node(i, x, y);
  68282. if (!last) {
  68283. p.prev = p;
  68284. p.next = p;
  68285. }
  68286. else {
  68287. p.next = last.next;
  68288. p.prev = last;
  68289. last.next.prev = p;
  68290. last.next = p;
  68291. }
  68292. return p;
  68293. }
  68294. function removeNode(p) {
  68295. p.next.prev = p.prev;
  68296. p.prev.next = p.next;
  68297. if (p.prevZ)
  68298. p.prevZ.nextZ = p.nextZ;
  68299. if (p.nextZ)
  68300. p.nextZ.prevZ = p.prevZ;
  68301. }
  68302. /**
  68303. * return a percentage difference between the polygon area and its triangulation area;
  68304. * used to verify correctness of triangulation
  68305. */
  68306. function deviation(data, holeIndices, dim, triangles) {
  68307. var hasHoles = holeIndices && holeIndices.length;
  68308. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  68309. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  68310. if (hasHoles) {
  68311. for (var i = 0, len = holeIndices.length; i < len; i++) {
  68312. var start = holeIndices[i] * dim;
  68313. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68314. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  68315. }
  68316. }
  68317. var trianglesArea = 0;
  68318. for (i = 0; i < triangles.length; i += 3) {
  68319. var a = triangles[i] * dim;
  68320. var b = triangles[i + 1] * dim;
  68321. var c = triangles[i + 2] * dim;
  68322. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  68323. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  68324. }
  68325. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  68326. }
  68327. Earcut.deviation = deviation;
  68328. ;
  68329. function signedArea(data, start, end, dim) {
  68330. var sum = 0;
  68331. for (var i = start, j = end - dim; i < end; i += dim) {
  68332. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  68333. j = i;
  68334. }
  68335. return sum;
  68336. }
  68337. /**
  68338. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  68339. */
  68340. function flatten(data) {
  68341. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  68342. for (var i = 0; i < data.length; i++) {
  68343. for (var j = 0; j < data[i].length; j++) {
  68344. for (var d = 0; d < dim; d++)
  68345. result.vertices.push(data[i][j][d]);
  68346. }
  68347. if (i > 0) {
  68348. holeIndex += data[i - 1].length;
  68349. result.holes.push(holeIndex);
  68350. }
  68351. }
  68352. return result;
  68353. }
  68354. Earcut.flatten = flatten;
  68355. ;
  68356. })(Earcut || (Earcut = {}));
  68357. //# sourceMappingURL=babylon.earcut.js.map
  68358. var BABYLON;
  68359. (function (BABYLON) {
  68360. var IndexedVector2 = /** @class */ (function (_super) {
  68361. __extends(IndexedVector2, _super);
  68362. function IndexedVector2(original, index) {
  68363. var _this = _super.call(this, original.x, original.y) || this;
  68364. _this.index = index;
  68365. return _this;
  68366. }
  68367. return IndexedVector2;
  68368. }(BABYLON.Vector2));
  68369. var PolygonPoints = /** @class */ (function () {
  68370. function PolygonPoints() {
  68371. this.elements = new Array();
  68372. }
  68373. PolygonPoints.prototype.add = function (originalPoints) {
  68374. var _this = this;
  68375. var result = new Array();
  68376. originalPoints.forEach(function (point) {
  68377. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  68378. var newPoint = new IndexedVector2(point, _this.elements.length);
  68379. result.push(newPoint);
  68380. _this.elements.push(newPoint);
  68381. }
  68382. });
  68383. return result;
  68384. };
  68385. PolygonPoints.prototype.computeBounds = function () {
  68386. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68387. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68388. this.elements.forEach(function (point) {
  68389. // x
  68390. if (point.x < lmin.x) {
  68391. lmin.x = point.x;
  68392. }
  68393. else if (point.x > lmax.x) {
  68394. lmax.x = point.x;
  68395. }
  68396. // y
  68397. if (point.y < lmin.y) {
  68398. lmin.y = point.y;
  68399. }
  68400. else if (point.y > lmax.y) {
  68401. lmax.y = point.y;
  68402. }
  68403. });
  68404. return {
  68405. min: lmin,
  68406. max: lmax,
  68407. width: lmax.x - lmin.x,
  68408. height: lmax.y - lmin.y
  68409. };
  68410. };
  68411. return PolygonPoints;
  68412. }());
  68413. var Polygon = /** @class */ (function () {
  68414. function Polygon() {
  68415. }
  68416. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  68417. return [
  68418. new BABYLON.Vector2(xmin, ymin),
  68419. new BABYLON.Vector2(xmax, ymin),
  68420. new BABYLON.Vector2(xmax, ymax),
  68421. new BABYLON.Vector2(xmin, ymax)
  68422. ];
  68423. };
  68424. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  68425. if (cx === void 0) { cx = 0; }
  68426. if (cy === void 0) { cy = 0; }
  68427. if (numberOfSides === void 0) { numberOfSides = 32; }
  68428. var result = new Array();
  68429. var angle = 0;
  68430. var increment = (Math.PI * 2) / numberOfSides;
  68431. for (var i = 0; i < numberOfSides; i++) {
  68432. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  68433. angle -= increment;
  68434. }
  68435. return result;
  68436. };
  68437. Polygon.Parse = function (input) {
  68438. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  68439. var i, result = [];
  68440. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  68441. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  68442. }
  68443. return result;
  68444. };
  68445. Polygon.StartingAt = function (x, y) {
  68446. return BABYLON.Path2.StartingAt(x, y);
  68447. };
  68448. return Polygon;
  68449. }());
  68450. BABYLON.Polygon = Polygon;
  68451. var PolygonMeshBuilder = /** @class */ (function () {
  68452. function PolygonMeshBuilder(name, contours, scene) {
  68453. this._points = new PolygonPoints();
  68454. this._outlinepoints = new PolygonPoints();
  68455. this._holes = new Array();
  68456. this._epoints = new Array();
  68457. this._eholes = new Array();
  68458. this._name = name;
  68459. this._scene = scene;
  68460. var points;
  68461. if (contours instanceof BABYLON.Path2) {
  68462. points = contours.getPoints();
  68463. }
  68464. else {
  68465. points = contours;
  68466. }
  68467. this._addToepoint(points);
  68468. this._points.add(points);
  68469. this._outlinepoints.add(points);
  68470. }
  68471. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  68472. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  68473. var p = points_1[_i];
  68474. this._epoints.push(p.x, p.y);
  68475. }
  68476. };
  68477. PolygonMeshBuilder.prototype.addHole = function (hole) {
  68478. this._points.add(hole);
  68479. var holepoints = new PolygonPoints();
  68480. holepoints.add(hole);
  68481. this._holes.push(holepoints);
  68482. this._eholes.push(this._epoints.length / 2);
  68483. this._addToepoint(hole);
  68484. return this;
  68485. };
  68486. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  68487. var _this = this;
  68488. if (updatable === void 0) { updatable = false; }
  68489. if (depth === void 0) { depth = 0; }
  68490. var result = new BABYLON.Mesh(this._name, this._scene);
  68491. var normals = new Array();
  68492. var positions = new Array();
  68493. var uvs = new Array();
  68494. var bounds = this._points.computeBounds();
  68495. this._points.elements.forEach(function (p) {
  68496. normals.push(0, 1.0, 0);
  68497. positions.push(p.x, 0, p.y);
  68498. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  68499. });
  68500. var indices = new Array();
  68501. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  68502. for (var i = 0; i < res.length; i++) {
  68503. indices.push(res[i]);
  68504. }
  68505. if (depth > 0) {
  68506. var positionscount = (positions.length / 3); //get the current pointcount
  68507. this._points.elements.forEach(function (p) {
  68508. normals.push(0, -1.0, 0);
  68509. positions.push(p.x, -depth, p.y);
  68510. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  68511. });
  68512. var totalCount = indices.length;
  68513. for (var i = 0; i < totalCount; i += 3) {
  68514. var i0 = indices[i + 0];
  68515. var i1 = indices[i + 1];
  68516. var i2 = indices[i + 2];
  68517. indices.push(i2 + positionscount);
  68518. indices.push(i1 + positionscount);
  68519. indices.push(i0 + positionscount);
  68520. }
  68521. //Add the sides
  68522. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  68523. this._holes.forEach(function (hole) {
  68524. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  68525. });
  68526. }
  68527. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  68528. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  68529. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  68530. result.setIndices(indices);
  68531. return result;
  68532. };
  68533. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  68534. var StartIndex = positions.length / 3;
  68535. var ulength = 0;
  68536. for (var i = 0; i < points.elements.length; i++) {
  68537. var p = points.elements[i];
  68538. var p1;
  68539. if ((i + 1) > points.elements.length - 1) {
  68540. p1 = points.elements[0];
  68541. }
  68542. else {
  68543. p1 = points.elements[i + 1];
  68544. }
  68545. positions.push(p.x, 0, p.y);
  68546. positions.push(p.x, -depth, p.y);
  68547. positions.push(p1.x, 0, p1.y);
  68548. positions.push(p1.x, -depth, p1.y);
  68549. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  68550. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  68551. var v3 = v2.subtract(v1);
  68552. var v4 = new BABYLON.Vector3(0, 1, 0);
  68553. var vn = BABYLON.Vector3.Cross(v3, v4);
  68554. vn = vn.normalize();
  68555. uvs.push(ulength / bounds.width, 0);
  68556. uvs.push(ulength / bounds.width, 1);
  68557. ulength += v3.length();
  68558. uvs.push((ulength / bounds.width), 0);
  68559. uvs.push((ulength / bounds.width), 1);
  68560. if (!flip) {
  68561. normals.push(-vn.x, -vn.y, -vn.z);
  68562. normals.push(-vn.x, -vn.y, -vn.z);
  68563. normals.push(-vn.x, -vn.y, -vn.z);
  68564. normals.push(-vn.x, -vn.y, -vn.z);
  68565. indices.push(StartIndex);
  68566. indices.push(StartIndex + 1);
  68567. indices.push(StartIndex + 2);
  68568. indices.push(StartIndex + 1);
  68569. indices.push(StartIndex + 3);
  68570. indices.push(StartIndex + 2);
  68571. }
  68572. else {
  68573. normals.push(vn.x, vn.y, vn.z);
  68574. normals.push(vn.x, vn.y, vn.z);
  68575. normals.push(vn.x, vn.y, vn.z);
  68576. normals.push(vn.x, vn.y, vn.z);
  68577. indices.push(StartIndex);
  68578. indices.push(StartIndex + 2);
  68579. indices.push(StartIndex + 1);
  68580. indices.push(StartIndex + 1);
  68581. indices.push(StartIndex + 2);
  68582. indices.push(StartIndex + 3);
  68583. }
  68584. StartIndex += 4;
  68585. }
  68586. ;
  68587. };
  68588. return PolygonMeshBuilder;
  68589. }());
  68590. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  68591. })(BABYLON || (BABYLON = {}));
  68592. //# sourceMappingURL=babylon.polygonMesh.js.map
  68593. var BABYLON;
  68594. (function (BABYLON) {
  68595. // Unique ID when we import meshes from Babylon to CSG
  68596. var currentCSGMeshId = 0;
  68597. // # class Vertex
  68598. // Represents a vertex of a polygon. Use your own vertex class instead of this
  68599. // one to provide additional features like texture coordinates and vertex
  68600. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  68601. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  68602. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  68603. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  68604. // is not used anywhere else.
  68605. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  68606. var Vertex = /** @class */ (function () {
  68607. function Vertex(pos, normal, uv) {
  68608. this.pos = pos;
  68609. this.normal = normal;
  68610. this.uv = uv;
  68611. }
  68612. Vertex.prototype.clone = function () {
  68613. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  68614. };
  68615. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  68616. // orientation of a polygon is flipped.
  68617. Vertex.prototype.flip = function () {
  68618. this.normal = this.normal.scale(-1);
  68619. };
  68620. // Create a new vertex between this vertex and `other` by linearly
  68621. // interpolating all properties using a parameter of `t`. Subclasses should
  68622. // override this to interpolate additional properties.
  68623. Vertex.prototype.interpolate = function (other, t) {
  68624. 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));
  68625. };
  68626. return Vertex;
  68627. }());
  68628. // # class Plane
  68629. // Represents a plane in 3D space.
  68630. var Plane = /** @class */ (function () {
  68631. function Plane(normal, w) {
  68632. this.normal = normal;
  68633. this.w = w;
  68634. }
  68635. Plane.FromPoints = function (a, b, c) {
  68636. var v0 = c.subtract(a);
  68637. var v1 = b.subtract(a);
  68638. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  68639. return null;
  68640. }
  68641. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  68642. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  68643. };
  68644. Plane.prototype.clone = function () {
  68645. return new Plane(this.normal.clone(), this.w);
  68646. };
  68647. Plane.prototype.flip = function () {
  68648. this.normal.scaleInPlace(-1);
  68649. this.w = -this.w;
  68650. };
  68651. // Split `polygon` by this plane if needed, then put the polygon or polygon
  68652. // fragments in the appropriate lists. Coplanar polygons go into either
  68653. // `coplanarFront` or `coplanarBack` depending on their orientation with
  68654. // respect to this plane. Polygons in front or in back of this plane go into
  68655. // either `front` or `back`.
  68656. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  68657. var COPLANAR = 0;
  68658. var FRONT = 1;
  68659. var BACK = 2;
  68660. var SPANNING = 3;
  68661. // Classify each point as well as the entire polygon into one of the above
  68662. // four classes.
  68663. var polygonType = 0;
  68664. var types = [];
  68665. var i;
  68666. var t;
  68667. for (i = 0; i < polygon.vertices.length; i++) {
  68668. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  68669. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  68670. polygonType |= type;
  68671. types.push(type);
  68672. }
  68673. // Put the polygon in the correct list, splitting it when necessary.
  68674. switch (polygonType) {
  68675. case COPLANAR:
  68676. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  68677. break;
  68678. case FRONT:
  68679. front.push(polygon);
  68680. break;
  68681. case BACK:
  68682. back.push(polygon);
  68683. break;
  68684. case SPANNING:
  68685. var f = [], b = [];
  68686. for (i = 0; i < polygon.vertices.length; i++) {
  68687. var j = (i + 1) % polygon.vertices.length;
  68688. var ti = types[i], tj = types[j];
  68689. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  68690. if (ti !== BACK)
  68691. f.push(vi);
  68692. if (ti !== FRONT)
  68693. b.push(ti !== BACK ? vi.clone() : vi);
  68694. if ((ti | tj) === SPANNING) {
  68695. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  68696. var v = vi.interpolate(vj, t);
  68697. f.push(v);
  68698. b.push(v.clone());
  68699. }
  68700. }
  68701. var poly;
  68702. if (f.length >= 3) {
  68703. poly = new Polygon(f, polygon.shared);
  68704. if (poly.plane)
  68705. front.push(poly);
  68706. }
  68707. if (b.length >= 3) {
  68708. poly = new Polygon(b, polygon.shared);
  68709. if (poly.plane)
  68710. back.push(poly);
  68711. }
  68712. break;
  68713. }
  68714. };
  68715. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  68716. // point is on the plane.
  68717. Plane.EPSILON = 1e-5;
  68718. return Plane;
  68719. }());
  68720. // # class Polygon
  68721. // Represents a convex polygon. The vertices used to initialize a polygon must
  68722. // be coplanar and form a convex loop.
  68723. //
  68724. // Each convex polygon has a `shared` property, which is shared between all
  68725. // polygons that are clones of each other or were split from the same polygon.
  68726. // This can be used to define per-polygon properties (such as surface color).
  68727. var Polygon = /** @class */ (function () {
  68728. function Polygon(vertices, shared) {
  68729. this.vertices = vertices;
  68730. this.shared = shared;
  68731. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  68732. }
  68733. Polygon.prototype.clone = function () {
  68734. var vertices = this.vertices.map(function (v) { return v.clone(); });
  68735. return new Polygon(vertices, this.shared);
  68736. };
  68737. Polygon.prototype.flip = function () {
  68738. this.vertices.reverse().map(function (v) { v.flip(); });
  68739. this.plane.flip();
  68740. };
  68741. return Polygon;
  68742. }());
  68743. // # class Node
  68744. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  68745. // by picking a polygon to split along. That polygon (and all other coplanar
  68746. // polygons) are added directly to that node and the other polygons are added to
  68747. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  68748. // no distinction between internal and leaf nodes.
  68749. var Node = /** @class */ (function () {
  68750. function Node(polygons) {
  68751. this.plane = null;
  68752. this.front = null;
  68753. this.back = null;
  68754. this.polygons = new Array();
  68755. if (polygons) {
  68756. this.build(polygons);
  68757. }
  68758. }
  68759. Node.prototype.clone = function () {
  68760. var node = new Node();
  68761. node.plane = this.plane && this.plane.clone();
  68762. node.front = this.front && this.front.clone();
  68763. node.back = this.back && this.back.clone();
  68764. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  68765. return node;
  68766. };
  68767. // Convert solid space to empty space and empty space to solid space.
  68768. Node.prototype.invert = function () {
  68769. for (var i = 0; i < this.polygons.length; i++) {
  68770. this.polygons[i].flip();
  68771. }
  68772. if (this.plane) {
  68773. this.plane.flip();
  68774. }
  68775. if (this.front) {
  68776. this.front.invert();
  68777. }
  68778. if (this.back) {
  68779. this.back.invert();
  68780. }
  68781. var temp = this.front;
  68782. this.front = this.back;
  68783. this.back = temp;
  68784. };
  68785. // Recursively remove all polygons in `polygons` that are inside this BSP
  68786. // tree.
  68787. Node.prototype.clipPolygons = function (polygons) {
  68788. if (!this.plane)
  68789. return polygons.slice();
  68790. var front = new Array(), back = new Array();
  68791. for (var i = 0; i < polygons.length; i++) {
  68792. this.plane.splitPolygon(polygons[i], front, back, front, back);
  68793. }
  68794. if (this.front) {
  68795. front = this.front.clipPolygons(front);
  68796. }
  68797. if (this.back) {
  68798. back = this.back.clipPolygons(back);
  68799. }
  68800. else {
  68801. back = [];
  68802. }
  68803. return front.concat(back);
  68804. };
  68805. // Remove all polygons in this BSP tree that are inside the other BSP tree
  68806. // `bsp`.
  68807. Node.prototype.clipTo = function (bsp) {
  68808. this.polygons = bsp.clipPolygons(this.polygons);
  68809. if (this.front)
  68810. this.front.clipTo(bsp);
  68811. if (this.back)
  68812. this.back.clipTo(bsp);
  68813. };
  68814. // Return a list of all polygons in this BSP tree.
  68815. Node.prototype.allPolygons = function () {
  68816. var polygons = this.polygons.slice();
  68817. if (this.front)
  68818. polygons = polygons.concat(this.front.allPolygons());
  68819. if (this.back)
  68820. polygons = polygons.concat(this.back.allPolygons());
  68821. return polygons;
  68822. };
  68823. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  68824. // new polygons are filtered down to the bottom of the tree and become new
  68825. // nodes there. Each set of polygons is partitioned using the first polygon
  68826. // (no heuristic is used to pick a good split).
  68827. Node.prototype.build = function (polygons) {
  68828. if (!polygons.length)
  68829. return;
  68830. if (!this.plane)
  68831. this.plane = polygons[0].plane.clone();
  68832. var front = new Array(), back = new Array();
  68833. for (var i = 0; i < polygons.length; i++) {
  68834. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  68835. }
  68836. if (front.length) {
  68837. if (!this.front)
  68838. this.front = new Node();
  68839. this.front.build(front);
  68840. }
  68841. if (back.length) {
  68842. if (!this.back)
  68843. this.back = new Node();
  68844. this.back.build(back);
  68845. }
  68846. };
  68847. return Node;
  68848. }());
  68849. var CSG = /** @class */ (function () {
  68850. function CSG() {
  68851. this.polygons = new Array();
  68852. }
  68853. // Convert BABYLON.Mesh to BABYLON.CSG
  68854. CSG.FromMesh = function (mesh) {
  68855. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  68856. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  68857. if (mesh instanceof BABYLON.Mesh) {
  68858. mesh.computeWorldMatrix(true);
  68859. matrix = mesh.getWorldMatrix();
  68860. meshPosition = mesh.position.clone();
  68861. meshRotation = mesh.rotation.clone();
  68862. if (mesh.rotationQuaternion) {
  68863. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  68864. }
  68865. meshScaling = mesh.scaling.clone();
  68866. }
  68867. else {
  68868. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  68869. }
  68870. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  68871. var subMeshes = mesh.subMeshes;
  68872. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  68873. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  68874. vertices = [];
  68875. for (var j = 0; j < 3; j++) {
  68876. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  68877. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  68878. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  68879. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  68880. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  68881. vertex = new Vertex(position, normal, uv);
  68882. vertices.push(vertex);
  68883. }
  68884. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  68885. // To handle the case of degenerated triangle
  68886. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  68887. if (polygon.plane)
  68888. polygons.push(polygon);
  68889. }
  68890. }
  68891. var csg = CSG.FromPolygons(polygons);
  68892. csg.matrix = matrix;
  68893. csg.position = meshPosition;
  68894. csg.rotation = meshRotation;
  68895. csg.scaling = meshScaling;
  68896. csg.rotationQuaternion = meshRotationQuaternion;
  68897. currentCSGMeshId++;
  68898. return csg;
  68899. };
  68900. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  68901. CSG.FromPolygons = function (polygons) {
  68902. var csg = new CSG();
  68903. csg.polygons = polygons;
  68904. return csg;
  68905. };
  68906. CSG.prototype.clone = function () {
  68907. var csg = new CSG();
  68908. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  68909. csg.copyTransformAttributes(this);
  68910. return csg;
  68911. };
  68912. CSG.prototype.union = function (csg) {
  68913. var a = new Node(this.clone().polygons);
  68914. var b = new Node(csg.clone().polygons);
  68915. a.clipTo(b);
  68916. b.clipTo(a);
  68917. b.invert();
  68918. b.clipTo(a);
  68919. b.invert();
  68920. a.build(b.allPolygons());
  68921. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  68922. };
  68923. CSG.prototype.unionInPlace = function (csg) {
  68924. var a = new Node(this.polygons);
  68925. var b = new Node(csg.polygons);
  68926. a.clipTo(b);
  68927. b.clipTo(a);
  68928. b.invert();
  68929. b.clipTo(a);
  68930. b.invert();
  68931. a.build(b.allPolygons());
  68932. this.polygons = a.allPolygons();
  68933. };
  68934. CSG.prototype.subtract = function (csg) {
  68935. var a = new Node(this.clone().polygons);
  68936. var b = new Node(csg.clone().polygons);
  68937. a.invert();
  68938. a.clipTo(b);
  68939. b.clipTo(a);
  68940. b.invert();
  68941. b.clipTo(a);
  68942. b.invert();
  68943. a.build(b.allPolygons());
  68944. a.invert();
  68945. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  68946. };
  68947. CSG.prototype.subtractInPlace = function (csg) {
  68948. var a = new Node(this.polygons);
  68949. var b = new Node(csg.polygons);
  68950. a.invert();
  68951. a.clipTo(b);
  68952. b.clipTo(a);
  68953. b.invert();
  68954. b.clipTo(a);
  68955. b.invert();
  68956. a.build(b.allPolygons());
  68957. a.invert();
  68958. this.polygons = a.allPolygons();
  68959. };
  68960. CSG.prototype.intersect = function (csg) {
  68961. var a = new Node(this.clone().polygons);
  68962. var b = new Node(csg.clone().polygons);
  68963. a.invert();
  68964. b.clipTo(a);
  68965. b.invert();
  68966. a.clipTo(b);
  68967. b.clipTo(a);
  68968. a.build(b.allPolygons());
  68969. a.invert();
  68970. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  68971. };
  68972. CSG.prototype.intersectInPlace = function (csg) {
  68973. var a = new Node(this.polygons);
  68974. var b = new Node(csg.polygons);
  68975. a.invert();
  68976. b.clipTo(a);
  68977. b.invert();
  68978. a.clipTo(b);
  68979. b.clipTo(a);
  68980. a.build(b.allPolygons());
  68981. a.invert();
  68982. this.polygons = a.allPolygons();
  68983. };
  68984. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  68985. // not modified.
  68986. CSG.prototype.inverse = function () {
  68987. var csg = this.clone();
  68988. csg.inverseInPlace();
  68989. return csg;
  68990. };
  68991. CSG.prototype.inverseInPlace = function () {
  68992. this.polygons.map(function (p) { p.flip(); });
  68993. };
  68994. // This is used to keep meshes transformations so they can be restored
  68995. // when we build back a Babylon Mesh
  68996. // NB : All CSG operations are performed in world coordinates
  68997. CSG.prototype.copyTransformAttributes = function (csg) {
  68998. this.matrix = csg.matrix;
  68999. this.position = csg.position;
  69000. this.rotation = csg.rotation;
  69001. this.scaling = csg.scaling;
  69002. this.rotationQuaternion = csg.rotationQuaternion;
  69003. return this;
  69004. };
  69005. // Build Raw mesh from CSG
  69006. // Coordinates here are in world space
  69007. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69008. var matrix = this.matrix.clone();
  69009. matrix.invert();
  69010. 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;
  69011. if (keepSubMeshes) {
  69012. // Sort Polygons, since subMeshes are indices range
  69013. polygons.sort(function (a, b) {
  69014. if (a.shared.meshId === b.shared.meshId) {
  69015. return a.shared.subMeshId - b.shared.subMeshId;
  69016. }
  69017. else {
  69018. return a.shared.meshId - b.shared.meshId;
  69019. }
  69020. });
  69021. }
  69022. for (var i = 0, il = polygons.length; i < il; i++) {
  69023. polygon = polygons[i];
  69024. // Building SubMeshes
  69025. if (!subMesh_dict[polygon.shared.meshId]) {
  69026. subMesh_dict[polygon.shared.meshId] = {};
  69027. }
  69028. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69029. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69030. indexStart: +Infinity,
  69031. indexEnd: -Infinity,
  69032. materialIndex: polygon.shared.materialIndex
  69033. };
  69034. }
  69035. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69036. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69037. polygonIndices[0] = 0;
  69038. polygonIndices[1] = j - 1;
  69039. polygonIndices[2] = j;
  69040. for (var k = 0; k < 3; k++) {
  69041. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69042. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69043. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69044. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69045. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69046. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69047. // Check if 2 points can be merged
  69048. if (!(typeof vertex_idx !== 'undefined' &&
  69049. normals[vertex_idx * 3] === localNormal.x &&
  69050. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69051. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69052. uvs[vertex_idx * 2] === uv.x &&
  69053. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69054. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69055. uvs.push(uv.x, uv.y);
  69056. normals.push(normal.x, normal.y, normal.z);
  69057. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69058. }
  69059. indices.push(vertex_idx);
  69060. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69061. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69062. currentIndex++;
  69063. }
  69064. }
  69065. }
  69066. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69067. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69068. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69069. mesh.setIndices(indices, null);
  69070. if (keepSubMeshes) {
  69071. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69072. var materialIndexOffset = 0, materialMaxIndex;
  69073. mesh.subMeshes = new Array();
  69074. for (var m in subMesh_dict) {
  69075. materialMaxIndex = -1;
  69076. for (var sm in subMesh_dict[m]) {
  69077. subMesh_obj = subMesh_dict[m][sm];
  69078. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69079. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69080. }
  69081. materialIndexOffset += ++materialMaxIndex;
  69082. }
  69083. }
  69084. return mesh;
  69085. };
  69086. // Build Mesh from CSG taking material and transforms into account
  69087. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69088. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69089. mesh.material = material;
  69090. mesh.position.copyFrom(this.position);
  69091. mesh.rotation.copyFrom(this.rotation);
  69092. if (this.rotationQuaternion) {
  69093. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69094. }
  69095. mesh.scaling.copyFrom(this.scaling);
  69096. mesh.computeWorldMatrix(true);
  69097. return mesh;
  69098. };
  69099. return CSG;
  69100. }());
  69101. BABYLON.CSG = CSG;
  69102. })(BABYLON || (BABYLON = {}));
  69103. //# sourceMappingURL=babylon.csg.js.map
  69104. var BABYLON;
  69105. (function (BABYLON) {
  69106. var LensFlare = /** @class */ (function () {
  69107. function LensFlare(size, position, color, imgUrl, system) {
  69108. this.size = size;
  69109. this.position = position;
  69110. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69111. this.color = color || new BABYLON.Color3(1, 1, 1);
  69112. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69113. this._system = system;
  69114. system.lensFlares.push(this);
  69115. }
  69116. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69117. return new LensFlare(size, position, color, imgUrl, system);
  69118. };
  69119. LensFlare.prototype.dispose = function () {
  69120. if (this.texture) {
  69121. this.texture.dispose();
  69122. }
  69123. // Remove from scene
  69124. var index = this._system.lensFlares.indexOf(this);
  69125. this._system.lensFlares.splice(index, 1);
  69126. };
  69127. ;
  69128. return LensFlare;
  69129. }());
  69130. BABYLON.LensFlare = LensFlare;
  69131. })(BABYLON || (BABYLON = {}));
  69132. //# sourceMappingURL=babylon.lensFlare.js.map
  69133. var BABYLON;
  69134. (function (BABYLON) {
  69135. var LensFlareSystem = /** @class */ (function () {
  69136. function LensFlareSystem(name, emitter, scene) {
  69137. this.name = name;
  69138. this.lensFlares = new Array();
  69139. this.borderLimit = 300;
  69140. this.viewportBorder = 0;
  69141. this.layerMask = 0x0FFFFFFF;
  69142. this._vertexBuffers = {};
  69143. this._isEnabled = true;
  69144. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69145. this._emitter = emitter;
  69146. this.id = name;
  69147. scene.lensFlareSystems.push(this);
  69148. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69149. var engine = scene.getEngine();
  69150. // VBO
  69151. var vertices = [];
  69152. vertices.push(1, 1);
  69153. vertices.push(-1, 1);
  69154. vertices.push(-1, -1);
  69155. vertices.push(1, -1);
  69156. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69157. // Indices
  69158. var indices = [];
  69159. indices.push(0);
  69160. indices.push(1);
  69161. indices.push(2);
  69162. indices.push(0);
  69163. indices.push(2);
  69164. indices.push(3);
  69165. this._indexBuffer = engine.createIndexBuffer(indices);
  69166. // Effects
  69167. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69168. }
  69169. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69170. get: function () {
  69171. return this._isEnabled;
  69172. },
  69173. set: function (value) {
  69174. this._isEnabled = value;
  69175. },
  69176. enumerable: true,
  69177. configurable: true
  69178. });
  69179. LensFlareSystem.prototype.getScene = function () {
  69180. return this._scene;
  69181. };
  69182. LensFlareSystem.prototype.getEmitter = function () {
  69183. return this._emitter;
  69184. };
  69185. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69186. this._emitter = newEmitter;
  69187. };
  69188. LensFlareSystem.prototype.getEmitterPosition = function () {
  69189. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69190. };
  69191. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69192. var position = this.getEmitterPosition();
  69193. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69194. this._positionX = position.x;
  69195. this._positionY = position.y;
  69196. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69197. if (this.viewportBorder > 0) {
  69198. globalViewport.x -= this.viewportBorder;
  69199. globalViewport.y -= this.viewportBorder;
  69200. globalViewport.width += this.viewportBorder * 2;
  69201. globalViewport.height += this.viewportBorder * 2;
  69202. position.x += this.viewportBorder;
  69203. position.y += this.viewportBorder;
  69204. this._positionX += this.viewportBorder;
  69205. this._positionY += this.viewportBorder;
  69206. }
  69207. if (position.z > 0) {
  69208. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69209. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69210. return true;
  69211. }
  69212. return true;
  69213. }
  69214. return false;
  69215. };
  69216. LensFlareSystem.prototype._isVisible = function () {
  69217. if (!this._isEnabled || !this._scene.activeCamera) {
  69218. return false;
  69219. }
  69220. var emitterPosition = this.getEmitterPosition();
  69221. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69222. var distance = direction.length();
  69223. direction.normalize();
  69224. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69225. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69226. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69227. };
  69228. LensFlareSystem.prototype.render = function () {
  69229. if (!this._effect.isReady() || !this._scene.activeCamera)
  69230. return false;
  69231. var engine = this._scene.getEngine();
  69232. var viewport = this._scene.activeCamera.viewport;
  69233. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  69234. // Position
  69235. if (!this.computeEffectivePosition(globalViewport)) {
  69236. return false;
  69237. }
  69238. // Visibility
  69239. if (!this._isVisible()) {
  69240. return false;
  69241. }
  69242. // Intensity
  69243. var awayX;
  69244. var awayY;
  69245. if (this._positionX < this.borderLimit + globalViewport.x) {
  69246. awayX = this.borderLimit + globalViewport.x - this._positionX;
  69247. }
  69248. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  69249. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  69250. }
  69251. else {
  69252. awayX = 0;
  69253. }
  69254. if (this._positionY < this.borderLimit + globalViewport.y) {
  69255. awayY = this.borderLimit + globalViewport.y - this._positionY;
  69256. }
  69257. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  69258. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  69259. }
  69260. else {
  69261. awayY = 0;
  69262. }
  69263. var away = (awayX > awayY) ? awayX : awayY;
  69264. away -= this.viewportBorder;
  69265. if (away > this.borderLimit) {
  69266. away = this.borderLimit;
  69267. }
  69268. var intensity = 1.0 - (away / this.borderLimit);
  69269. if (intensity < 0) {
  69270. return false;
  69271. }
  69272. if (intensity > 1.0) {
  69273. intensity = 1.0;
  69274. }
  69275. if (this.viewportBorder > 0) {
  69276. globalViewport.x += this.viewportBorder;
  69277. globalViewport.y += this.viewportBorder;
  69278. globalViewport.width -= this.viewportBorder * 2;
  69279. globalViewport.height -= this.viewportBorder * 2;
  69280. this._positionX -= this.viewportBorder;
  69281. this._positionY -= this.viewportBorder;
  69282. }
  69283. // Position
  69284. var centerX = globalViewport.x + globalViewport.width / 2;
  69285. var centerY = globalViewport.y + globalViewport.height / 2;
  69286. var distX = centerX - this._positionX;
  69287. var distY = centerY - this._positionY;
  69288. // Effects
  69289. engine.enableEffect(this._effect);
  69290. engine.setState(false);
  69291. engine.setDepthBuffer(false);
  69292. // VBOs
  69293. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69294. // Flares
  69295. for (var index = 0; index < this.lensFlares.length; index++) {
  69296. var flare = this.lensFlares[index];
  69297. engine.setAlphaMode(flare.alphaMode);
  69298. var x = centerX - (distX * flare.position);
  69299. var y = centerY - (distY * flare.position);
  69300. var cw = flare.size;
  69301. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  69302. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  69303. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  69304. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  69305. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  69306. // Texture
  69307. this._effect.setTexture("textureSampler", flare.texture);
  69308. // Color
  69309. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  69310. // Draw order
  69311. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69312. }
  69313. engine.setDepthBuffer(true);
  69314. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69315. return true;
  69316. };
  69317. LensFlareSystem.prototype.dispose = function () {
  69318. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69319. if (vertexBuffer) {
  69320. vertexBuffer.dispose();
  69321. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69322. }
  69323. if (this._indexBuffer) {
  69324. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69325. this._indexBuffer = null;
  69326. }
  69327. while (this.lensFlares.length) {
  69328. this.lensFlares[0].dispose();
  69329. }
  69330. // Remove from scene
  69331. var index = this._scene.lensFlareSystems.indexOf(this);
  69332. this._scene.lensFlareSystems.splice(index, 1);
  69333. };
  69334. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  69335. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  69336. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  69337. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  69338. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  69339. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  69340. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  69341. var parsedFlare = parsedLensFlareSystem.flares[index];
  69342. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  69343. }
  69344. return lensFlareSystem;
  69345. };
  69346. LensFlareSystem.prototype.serialize = function () {
  69347. var serializationObject = {};
  69348. serializationObject.id = this.id;
  69349. serializationObject.name = this.name;
  69350. serializationObject.emitterId = this.getEmitter().id;
  69351. serializationObject.borderLimit = this.borderLimit;
  69352. serializationObject.flares = [];
  69353. for (var index = 0; index < this.lensFlares.length; index++) {
  69354. var flare = this.lensFlares[index];
  69355. serializationObject.flares.push({
  69356. size: flare.size,
  69357. position: flare.position,
  69358. color: flare.color.asArray(),
  69359. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  69360. });
  69361. }
  69362. return serializationObject;
  69363. };
  69364. return LensFlareSystem;
  69365. }());
  69366. BABYLON.LensFlareSystem = LensFlareSystem;
  69367. })(BABYLON || (BABYLON = {}));
  69368. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  69369. var BABYLON;
  69370. (function (BABYLON) {
  69371. /**
  69372. * This is a holder class for the physics joint created by the physics plugin.
  69373. * It holds a set of functions to control the underlying joint.
  69374. */
  69375. var PhysicsJoint = /** @class */ (function () {
  69376. function PhysicsJoint(type, jointData) {
  69377. this.type = type;
  69378. this.jointData = jointData;
  69379. jointData.nativeParams = jointData.nativeParams || {};
  69380. }
  69381. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  69382. get: function () {
  69383. return this._physicsJoint;
  69384. },
  69385. set: function (newJoint) {
  69386. if (this._physicsJoint) {
  69387. //remove from the wolrd
  69388. }
  69389. this._physicsJoint = newJoint;
  69390. },
  69391. enumerable: true,
  69392. configurable: true
  69393. });
  69394. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  69395. set: function (physicsPlugin) {
  69396. this._physicsPlugin = physicsPlugin;
  69397. },
  69398. enumerable: true,
  69399. configurable: true
  69400. });
  69401. /**
  69402. * Execute a function that is physics-plugin specific.
  69403. * @param {Function} func the function that will be executed.
  69404. * It accepts two parameters: the physics world and the physics joint.
  69405. */
  69406. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  69407. func(this._physicsPlugin.world, this._physicsJoint);
  69408. };
  69409. //TODO check if the native joints are the same
  69410. //Joint Types
  69411. PhysicsJoint.DistanceJoint = 0;
  69412. PhysicsJoint.HingeJoint = 1;
  69413. PhysicsJoint.BallAndSocketJoint = 2;
  69414. PhysicsJoint.WheelJoint = 3;
  69415. PhysicsJoint.SliderJoint = 4;
  69416. //OIMO
  69417. PhysicsJoint.PrismaticJoint = 5;
  69418. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  69419. PhysicsJoint.UniversalJoint = 6;
  69420. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  69421. //Cannon
  69422. //Similar to a Ball-Joint. Different in params
  69423. PhysicsJoint.PointToPointJoint = 8;
  69424. //Cannon only at the moment
  69425. PhysicsJoint.SpringJoint = 9;
  69426. PhysicsJoint.LockJoint = 10;
  69427. return PhysicsJoint;
  69428. }());
  69429. BABYLON.PhysicsJoint = PhysicsJoint;
  69430. /**
  69431. * A class representing a physics distance joint.
  69432. */
  69433. var DistanceJoint = /** @class */ (function (_super) {
  69434. __extends(DistanceJoint, _super);
  69435. function DistanceJoint(jointData) {
  69436. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  69437. }
  69438. /**
  69439. * Update the predefined distance.
  69440. */
  69441. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  69442. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  69443. };
  69444. return DistanceJoint;
  69445. }(PhysicsJoint));
  69446. BABYLON.DistanceJoint = DistanceJoint;
  69447. var MotorEnabledJoint = /** @class */ (function (_super) {
  69448. __extends(MotorEnabledJoint, _super);
  69449. function MotorEnabledJoint(type, jointData) {
  69450. return _super.call(this, type, jointData) || this;
  69451. }
  69452. /**
  69453. * Set the motor values.
  69454. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69455. * @param {number} force the force to apply
  69456. * @param {number} maxForce max force for this motor.
  69457. */
  69458. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  69459. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69460. };
  69461. /**
  69462. * Set the motor's limits.
  69463. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69464. */
  69465. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69466. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69467. };
  69468. return MotorEnabledJoint;
  69469. }(PhysicsJoint));
  69470. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  69471. /**
  69472. * This class represents a single hinge physics joint
  69473. */
  69474. var HingeJoint = /** @class */ (function (_super) {
  69475. __extends(HingeJoint, _super);
  69476. function HingeJoint(jointData) {
  69477. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  69478. }
  69479. /**
  69480. * Set the motor values.
  69481. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69482. * @param {number} force the force to apply
  69483. * @param {number} maxForce max force for this motor.
  69484. */
  69485. HingeJoint.prototype.setMotor = function (force, maxForce) {
  69486. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69487. };
  69488. /**
  69489. * Set the motor's limits.
  69490. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69491. */
  69492. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69493. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69494. };
  69495. return HingeJoint;
  69496. }(MotorEnabledJoint));
  69497. BABYLON.HingeJoint = HingeJoint;
  69498. /**
  69499. * This class represents a dual hinge physics joint (same as wheel joint)
  69500. */
  69501. var Hinge2Joint = /** @class */ (function (_super) {
  69502. __extends(Hinge2Joint, _super);
  69503. function Hinge2Joint(jointData) {
  69504. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  69505. }
  69506. /**
  69507. * Set the motor values.
  69508. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69509. * @param {number} force the force to apply
  69510. * @param {number} maxForce max force for this motor.
  69511. * @param {motorIndex} the motor's index, 0 or 1.
  69512. */
  69513. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  69514. if (motorIndex === void 0) { motorIndex = 0; }
  69515. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  69516. };
  69517. /**
  69518. * Set the motor limits.
  69519. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69520. * @param {number} upperLimit the upper limit
  69521. * @param {number} lowerLimit lower limit
  69522. * @param {motorIndex} the motor's index, 0 or 1.
  69523. */
  69524. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  69525. if (motorIndex === void 0) { motorIndex = 0; }
  69526. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  69527. };
  69528. return Hinge2Joint;
  69529. }(MotorEnabledJoint));
  69530. BABYLON.Hinge2Joint = Hinge2Joint;
  69531. })(BABYLON || (BABYLON = {}));
  69532. //# sourceMappingURL=babylon.physicsJoint.js.map
  69533. var BABYLON;
  69534. (function (BABYLON) {
  69535. var PhysicsImpostor = /** @class */ (function () {
  69536. function PhysicsImpostor(object, type, _options, _scene) {
  69537. if (_options === void 0) { _options = { mass: 0 }; }
  69538. var _this = this;
  69539. this.object = object;
  69540. this.type = type;
  69541. this._options = _options;
  69542. this._scene = _scene;
  69543. this._bodyUpdateRequired = false;
  69544. this._onBeforePhysicsStepCallbacks = new Array();
  69545. this._onAfterPhysicsStepCallbacks = new Array();
  69546. this._onPhysicsCollideCallbacks = [];
  69547. this._deltaPosition = BABYLON.Vector3.Zero();
  69548. this._isDisposed = false;
  69549. //temp variables for parent rotation calculations
  69550. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  69551. this._tmpQuat = new BABYLON.Quaternion();
  69552. this._tmpQuat2 = new BABYLON.Quaternion();
  69553. /**
  69554. * this function is executed by the physics engine.
  69555. */
  69556. this.beforeStep = function () {
  69557. if (!_this._physicsEngine) {
  69558. return;
  69559. }
  69560. _this.object.translate(_this._deltaPosition, -1);
  69561. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  69562. _this.object.computeWorldMatrix(false);
  69563. if (_this.object.parent && _this.object.rotationQuaternion) {
  69564. _this.getParentsRotation();
  69565. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  69566. }
  69567. else {
  69568. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  69569. }
  69570. if (!_this._options.disableBidirectionalTransformation) {
  69571. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  69572. }
  69573. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  69574. func(_this);
  69575. });
  69576. };
  69577. /**
  69578. * this function is executed by the physics engine.
  69579. */
  69580. this.afterStep = function () {
  69581. if (!_this._physicsEngine) {
  69582. return;
  69583. }
  69584. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  69585. func(_this);
  69586. });
  69587. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  69588. // object has now its world rotation. needs to be converted to local.
  69589. if (_this.object.parent && _this.object.rotationQuaternion) {
  69590. _this.getParentsRotation();
  69591. _this._tmpQuat.conjugateInPlace();
  69592. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  69593. }
  69594. // take the position set and make it the absolute position of this object.
  69595. _this.object.setAbsolutePosition(_this.object.position);
  69596. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  69597. _this.object.translate(_this._deltaPosition, 1);
  69598. };
  69599. /**
  69600. * Legacy collision detection event support
  69601. */
  69602. this.onCollideEvent = null;
  69603. //event and body object due to cannon's event-based architecture.
  69604. this.onCollide = function (e) {
  69605. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  69606. return;
  69607. }
  69608. if (!_this._physicsEngine) {
  69609. return;
  69610. }
  69611. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  69612. if (otherImpostor) {
  69613. // Legacy collision detection event support
  69614. if (_this.onCollideEvent) {
  69615. _this.onCollideEvent(_this, otherImpostor);
  69616. }
  69617. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  69618. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  69619. }).forEach(function (obj) {
  69620. obj.callback(_this, otherImpostor);
  69621. });
  69622. }
  69623. };
  69624. //sanity check!
  69625. if (!this.object) {
  69626. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  69627. return;
  69628. }
  69629. //legacy support for old syntax.
  69630. if (!this._scene && object.getScene) {
  69631. this._scene = object.getScene();
  69632. }
  69633. if (!this._scene) {
  69634. return;
  69635. }
  69636. this._physicsEngine = this._scene.getPhysicsEngine();
  69637. if (!this._physicsEngine) {
  69638. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  69639. }
  69640. else {
  69641. //set the object's quaternion, if not set
  69642. if (!this.object.rotationQuaternion) {
  69643. if (this.object.rotation) {
  69644. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  69645. }
  69646. else {
  69647. this.object.rotationQuaternion = new BABYLON.Quaternion();
  69648. }
  69649. }
  69650. //default options params
  69651. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  69652. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  69653. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  69654. this._joints = [];
  69655. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  69656. if (!this.object.parent || this._options.ignoreParent) {
  69657. this._init();
  69658. }
  69659. else if (this.object.parent.physicsImpostor) {
  69660. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  69661. }
  69662. }
  69663. }
  69664. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  69665. get: function () {
  69666. return this._isDisposed;
  69667. },
  69668. enumerable: true,
  69669. configurable: true
  69670. });
  69671. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  69672. get: function () {
  69673. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  69674. },
  69675. set: function (value) {
  69676. this.setMass(value);
  69677. },
  69678. enumerable: true,
  69679. configurable: true
  69680. });
  69681. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  69682. get: function () {
  69683. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  69684. },
  69685. set: function (value) {
  69686. if (!this._physicsEngine) {
  69687. return;
  69688. }
  69689. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  69690. },
  69691. enumerable: true,
  69692. configurable: true
  69693. });
  69694. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  69695. get: function () {
  69696. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  69697. },
  69698. set: function (value) {
  69699. if (!this._physicsEngine) {
  69700. return;
  69701. }
  69702. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  69703. },
  69704. enumerable: true,
  69705. configurable: true
  69706. });
  69707. /**
  69708. * This function will completly initialize this impostor.
  69709. * It will create a new body - but only if this mesh has no parent.
  69710. * If it has, this impostor will not be used other than to define the impostor
  69711. * of the child mesh.
  69712. */
  69713. PhysicsImpostor.prototype._init = function () {
  69714. if (!this._physicsEngine) {
  69715. return;
  69716. }
  69717. this._physicsEngine.removeImpostor(this);
  69718. this.physicsBody = null;
  69719. this._parent = this._parent || this._getPhysicsParent();
  69720. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  69721. this._physicsEngine.addImpostor(this);
  69722. }
  69723. };
  69724. PhysicsImpostor.prototype._getPhysicsParent = function () {
  69725. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  69726. var parentMesh = this.object.parent;
  69727. return parentMesh.physicsImpostor;
  69728. }
  69729. return null;
  69730. };
  69731. /**
  69732. * Should a new body be generated.
  69733. */
  69734. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  69735. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  69736. };
  69737. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  69738. this.forceUpdate();
  69739. };
  69740. /**
  69741. * Force a regeneration of this or the parent's impostor's body.
  69742. * Use under cautious - This will remove all joints already implemented.
  69743. */
  69744. PhysicsImpostor.prototype.forceUpdate = function () {
  69745. this._init();
  69746. if (this.parent && !this._options.ignoreParent) {
  69747. this.parent.forceUpdate();
  69748. }
  69749. };
  69750. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  69751. /*public get mesh(): AbstractMesh {
  69752. return this._mesh;
  69753. }*/
  69754. /**
  69755. * Gets the body that holds this impostor. Either its own, or its parent.
  69756. */
  69757. get: function () {
  69758. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  69759. },
  69760. /**
  69761. * Set the physics body. Used mainly by the physics engine/plugin
  69762. */
  69763. set: function (physicsBody) {
  69764. if (this._physicsBody && this._physicsEngine) {
  69765. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  69766. }
  69767. this._physicsBody = physicsBody;
  69768. this.resetUpdateFlags();
  69769. },
  69770. enumerable: true,
  69771. configurable: true
  69772. });
  69773. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  69774. get: function () {
  69775. return !this._options.ignoreParent && this._parent ? this._parent : null;
  69776. },
  69777. set: function (value) {
  69778. this._parent = value;
  69779. },
  69780. enumerable: true,
  69781. configurable: true
  69782. });
  69783. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  69784. this._bodyUpdateRequired = false;
  69785. };
  69786. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  69787. if (this.object.getBoundingInfo) {
  69788. var q = this.object.rotationQuaternion;
  69789. //reset rotation
  69790. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  69791. //calculate the world matrix with no rotation
  69792. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69793. var boundingInfo = this.object.getBoundingInfo();
  69794. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  69795. //bring back the rotation
  69796. this.object.rotationQuaternion = q;
  69797. //calculate the world matrix with the new rotation
  69798. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  69799. return size;
  69800. }
  69801. else {
  69802. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  69803. }
  69804. };
  69805. PhysicsImpostor.prototype.getObjectCenter = function () {
  69806. if (this.object.getBoundingInfo) {
  69807. var boundingInfo = this.object.getBoundingInfo();
  69808. return boundingInfo.boundingBox.centerWorld;
  69809. }
  69810. else {
  69811. return this.object.position;
  69812. }
  69813. };
  69814. /**
  69815. * Get a specific parametes from the options parameter.
  69816. */
  69817. PhysicsImpostor.prototype.getParam = function (paramName) {
  69818. return this._options[paramName];
  69819. };
  69820. /**
  69821. * Sets a specific parameter in the options given to the physics plugin
  69822. */
  69823. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  69824. this._options[paramName] = value;
  69825. this._bodyUpdateRequired = true;
  69826. };
  69827. /**
  69828. * Specifically change the body's mass option. Won't recreate the physics body object
  69829. */
  69830. PhysicsImpostor.prototype.setMass = function (mass) {
  69831. if (this.getParam("mass") !== mass) {
  69832. this.setParam("mass", mass);
  69833. }
  69834. if (this._physicsEngine) {
  69835. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  69836. }
  69837. };
  69838. PhysicsImpostor.prototype.getLinearVelocity = function () {
  69839. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  69840. };
  69841. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  69842. if (this._physicsEngine) {
  69843. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  69844. }
  69845. };
  69846. PhysicsImpostor.prototype.getAngularVelocity = function () {
  69847. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  69848. };
  69849. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  69850. if (this._physicsEngine) {
  69851. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  69852. }
  69853. };
  69854. /**
  69855. * Execute a function with the physics plugin native code.
  69856. * Provide a function the will have two variables - the world object and the physics body object.
  69857. */
  69858. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  69859. if (this._physicsEngine) {
  69860. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  69861. }
  69862. };
  69863. /**
  69864. * Register a function that will be executed before the physics world is stepping forward.
  69865. */
  69866. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  69867. this._onBeforePhysicsStepCallbacks.push(func);
  69868. };
  69869. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  69870. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  69871. if (index > -1) {
  69872. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  69873. }
  69874. else {
  69875. BABYLON.Tools.Warn("Function to remove was not found");
  69876. }
  69877. };
  69878. /**
  69879. * Register a function that will be executed after the physics step
  69880. */
  69881. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  69882. this._onAfterPhysicsStepCallbacks.push(func);
  69883. };
  69884. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  69885. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  69886. if (index > -1) {
  69887. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  69888. }
  69889. else {
  69890. BABYLON.Tools.Warn("Function to remove was not found");
  69891. }
  69892. };
  69893. /**
  69894. * register a function that will be executed when this impostor collides against a different body.
  69895. */
  69896. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  69897. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  69898. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  69899. };
  69900. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  69901. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  69902. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  69903. if (index > -1) {
  69904. this._onPhysicsCollideCallbacks.splice(index, 1);
  69905. }
  69906. else {
  69907. BABYLON.Tools.Warn("Function to remove was not found");
  69908. }
  69909. };
  69910. PhysicsImpostor.prototype.getParentsRotation = function () {
  69911. var parent = this.object.parent;
  69912. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  69913. while (parent) {
  69914. if (parent.rotationQuaternion) {
  69915. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  69916. }
  69917. else {
  69918. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  69919. }
  69920. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  69921. parent = parent.parent;
  69922. }
  69923. return this._tmpQuat;
  69924. };
  69925. /**
  69926. * Apply a force
  69927. */
  69928. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  69929. if (this._physicsEngine) {
  69930. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  69931. }
  69932. return this;
  69933. };
  69934. /**
  69935. * Apply an impulse
  69936. */
  69937. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  69938. if (this._physicsEngine) {
  69939. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  69940. }
  69941. return this;
  69942. };
  69943. /**
  69944. * A help function to create a joint.
  69945. */
  69946. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  69947. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  69948. this.addJoint(otherImpostor, joint);
  69949. return this;
  69950. };
  69951. /**
  69952. * Add a joint to this impostor with a different impostor.
  69953. */
  69954. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  69955. this._joints.push({
  69956. otherImpostor: otherImpostor,
  69957. joint: joint
  69958. });
  69959. if (this._physicsEngine) {
  69960. this._physicsEngine.addJoint(this, otherImpostor, joint);
  69961. }
  69962. return this;
  69963. };
  69964. /**
  69965. * Will keep this body still, in a sleep mode.
  69966. */
  69967. PhysicsImpostor.prototype.sleep = function () {
  69968. if (this._physicsEngine) {
  69969. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  69970. }
  69971. return this;
  69972. };
  69973. /**
  69974. * Wake the body up.
  69975. */
  69976. PhysicsImpostor.prototype.wakeUp = function () {
  69977. if (this._physicsEngine) {
  69978. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  69979. }
  69980. return this;
  69981. };
  69982. PhysicsImpostor.prototype.clone = function (newObject) {
  69983. if (!newObject)
  69984. return null;
  69985. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  69986. };
  69987. PhysicsImpostor.prototype.dispose = function () {
  69988. var _this = this;
  69989. //no dispose if no physics engine is available.
  69990. if (!this._physicsEngine) {
  69991. return;
  69992. }
  69993. this._joints.forEach(function (j) {
  69994. if (_this._physicsEngine) {
  69995. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  69996. }
  69997. });
  69998. //dispose the physics body
  69999. this._physicsEngine.removeImpostor(this);
  70000. if (this.parent) {
  70001. this.parent.forceUpdate();
  70002. }
  70003. else {
  70004. /*this._object.getChildMeshes().forEach(function(mesh) {
  70005. if (mesh.physicsImpostor) {
  70006. if (disposeChildren) {
  70007. mesh.physicsImpostor.dispose();
  70008. mesh.physicsImpostor = null;
  70009. }
  70010. }
  70011. })*/
  70012. }
  70013. this._isDisposed = true;
  70014. };
  70015. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70016. this._deltaPosition.copyFrom(position);
  70017. };
  70018. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70019. if (!this._deltaRotation) {
  70020. this._deltaRotation = new BABYLON.Quaternion();
  70021. }
  70022. this._deltaRotation.copyFrom(rotation);
  70023. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70024. };
  70025. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70026. if (this._physicsEngine) {
  70027. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70028. }
  70029. return this;
  70030. };
  70031. PhysicsImpostor.prototype.getRadius = function () {
  70032. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70033. };
  70034. /**
  70035. * Sync a bone with this impostor
  70036. * @param bone The bone to sync to the impostor.
  70037. * @param boneMesh The mesh that the bone is influencing.
  70038. * @param jointPivot The pivot of the joint / bone in local space.
  70039. * @param distToJoint Optional distance from the impostor to the joint.
  70040. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70041. */
  70042. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70043. var tempVec = PhysicsImpostor._tmpVecs[0];
  70044. var mesh = this.object;
  70045. if (mesh.rotationQuaternion) {
  70046. if (adjustRotation) {
  70047. var tempQuat = PhysicsImpostor._tmpQuat;
  70048. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70049. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70050. }
  70051. else {
  70052. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70053. }
  70054. }
  70055. tempVec.x = 0;
  70056. tempVec.y = 0;
  70057. tempVec.z = 0;
  70058. if (jointPivot) {
  70059. tempVec.x = jointPivot.x;
  70060. tempVec.y = jointPivot.y;
  70061. tempVec.z = jointPivot.z;
  70062. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70063. if (distToJoint === undefined || distToJoint === null) {
  70064. distToJoint = jointPivot.length();
  70065. }
  70066. tempVec.x *= distToJoint;
  70067. tempVec.y *= distToJoint;
  70068. tempVec.z *= distToJoint;
  70069. }
  70070. if (bone.getParent()) {
  70071. tempVec.addInPlace(mesh.getAbsolutePosition());
  70072. bone.setAbsolutePosition(tempVec, boneMesh);
  70073. }
  70074. else {
  70075. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70076. boneMesh.position.x -= tempVec.x;
  70077. boneMesh.position.y -= tempVec.y;
  70078. boneMesh.position.z -= tempVec.z;
  70079. }
  70080. };
  70081. /**
  70082. * Sync impostor to a bone
  70083. * @param bone The bone that the impostor will be synced to.
  70084. * @param boneMesh The mesh that the bone is influencing.
  70085. * @param jointPivot The pivot of the joint / bone in local space.
  70086. * @param distToJoint Optional distance from the impostor to the joint.
  70087. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70088. * @param boneAxis Optional vector3 axis the bone is aligned with
  70089. */
  70090. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70091. var mesh = this.object;
  70092. if (mesh.rotationQuaternion) {
  70093. if (adjustRotation) {
  70094. var tempQuat = PhysicsImpostor._tmpQuat;
  70095. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70096. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70097. }
  70098. else {
  70099. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70100. }
  70101. }
  70102. var pos = PhysicsImpostor._tmpVecs[0];
  70103. var boneDir = PhysicsImpostor._tmpVecs[1];
  70104. if (!boneAxis) {
  70105. boneAxis = PhysicsImpostor._tmpVecs[2];
  70106. boneAxis.x = 0;
  70107. boneAxis.y = 1;
  70108. boneAxis.z = 0;
  70109. }
  70110. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70111. bone.getAbsolutePositionToRef(boneMesh, pos);
  70112. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70113. distToJoint = jointPivot.length();
  70114. }
  70115. if (distToJoint !== undefined && distToJoint !== null) {
  70116. pos.x += boneDir.x * distToJoint;
  70117. pos.y += boneDir.y * distToJoint;
  70118. pos.z += boneDir.z * distToJoint;
  70119. }
  70120. mesh.setAbsolutePosition(pos);
  70121. };
  70122. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70123. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70124. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70125. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70126. //Impostor types
  70127. PhysicsImpostor.NoImpostor = 0;
  70128. PhysicsImpostor.SphereImpostor = 1;
  70129. PhysicsImpostor.BoxImpostor = 2;
  70130. PhysicsImpostor.PlaneImpostor = 3;
  70131. PhysicsImpostor.MeshImpostor = 4;
  70132. PhysicsImpostor.CylinderImpostor = 7;
  70133. PhysicsImpostor.ParticleImpostor = 8;
  70134. PhysicsImpostor.HeightmapImpostor = 9;
  70135. return PhysicsImpostor;
  70136. }());
  70137. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70138. })(BABYLON || (BABYLON = {}));
  70139. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70140. var BABYLON;
  70141. (function (BABYLON) {
  70142. var PhysicsEngine = /** @class */ (function () {
  70143. function PhysicsEngine(gravity, _physicsPlugin) {
  70144. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70145. this._physicsPlugin = _physicsPlugin;
  70146. //new methods and parameters
  70147. this._impostors = [];
  70148. this._joints = [];
  70149. if (!this._physicsPlugin.isSupported()) {
  70150. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70151. + "Please make sure it is included.");
  70152. }
  70153. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70154. this.setGravity(gravity);
  70155. this.setTimeStep();
  70156. }
  70157. PhysicsEngine.prototype.setGravity = function (gravity) {
  70158. this.gravity = gravity;
  70159. this._physicsPlugin.setGravity(this.gravity);
  70160. };
  70161. /**
  70162. * Set the time step of the physics engine.
  70163. * default is 1/60.
  70164. * To slow it down, enter 1/600 for example.
  70165. * To speed it up, 1/30
  70166. * @param {number} newTimeStep the new timestep to apply to this world.
  70167. */
  70168. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70169. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70170. this._physicsPlugin.setTimeStep(newTimeStep);
  70171. };
  70172. /**
  70173. * Get the time step of the physics engine.
  70174. */
  70175. PhysicsEngine.prototype.getTimeStep = function () {
  70176. return this._physicsPlugin.getTimeStep();
  70177. };
  70178. PhysicsEngine.prototype.dispose = function () {
  70179. this._impostors.forEach(function (impostor) {
  70180. impostor.dispose();
  70181. });
  70182. this._physicsPlugin.dispose();
  70183. };
  70184. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70185. return this._physicsPlugin.name;
  70186. };
  70187. /**
  70188. * Adding a new impostor for the impostor tracking.
  70189. * This will be done by the impostor itself.
  70190. * @param {PhysicsImpostor} impostor the impostor to add
  70191. */
  70192. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70193. impostor.uniqueId = this._impostors.push(impostor);
  70194. //if no parent, generate the body
  70195. if (!impostor.parent) {
  70196. this._physicsPlugin.generatePhysicsBody(impostor);
  70197. }
  70198. };
  70199. /**
  70200. * Remove an impostor from the engine.
  70201. * This impostor and its mesh will not longer be updated by the physics engine.
  70202. * @param {PhysicsImpostor} impostor the impostor to remove
  70203. */
  70204. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70205. var index = this._impostors.indexOf(impostor);
  70206. if (index > -1) {
  70207. var removed = this._impostors.splice(index, 1);
  70208. //Is it needed?
  70209. if (removed.length) {
  70210. //this will also remove it from the world.
  70211. removed[0].physicsBody = null;
  70212. }
  70213. }
  70214. };
  70215. /**
  70216. * Add a joint to the physics engine
  70217. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70218. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70219. * @param {PhysicsJoint} the joint that will connect both impostors.
  70220. */
  70221. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70222. var impostorJoint = {
  70223. mainImpostor: mainImpostor,
  70224. connectedImpostor: connectedImpostor,
  70225. joint: joint
  70226. };
  70227. joint.physicsPlugin = this._physicsPlugin;
  70228. this._joints.push(impostorJoint);
  70229. this._physicsPlugin.generateJoint(impostorJoint);
  70230. };
  70231. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  70232. var matchingJoints = this._joints.filter(function (impostorJoint) {
  70233. return (impostorJoint.connectedImpostor === connectedImpostor
  70234. && impostorJoint.joint === joint
  70235. && impostorJoint.mainImpostor === mainImpostor);
  70236. });
  70237. if (matchingJoints.length) {
  70238. this._physicsPlugin.removeJoint(matchingJoints[0]);
  70239. //TODO remove it from the list as well
  70240. }
  70241. };
  70242. /**
  70243. * Called by the scene. no need to call it.
  70244. */
  70245. PhysicsEngine.prototype._step = function (delta) {
  70246. var _this = this;
  70247. //check if any mesh has no body / requires an update
  70248. this._impostors.forEach(function (impostor) {
  70249. if (impostor.isBodyInitRequired()) {
  70250. _this._physicsPlugin.generatePhysicsBody(impostor);
  70251. }
  70252. });
  70253. if (delta > 0.1) {
  70254. delta = 0.1;
  70255. }
  70256. else if (delta <= 0) {
  70257. delta = 1.0 / 60.0;
  70258. }
  70259. this._physicsPlugin.executeStep(delta, this._impostors);
  70260. };
  70261. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  70262. return this._physicsPlugin;
  70263. };
  70264. PhysicsEngine.prototype.getImpostors = function () {
  70265. return this._impostors;
  70266. };
  70267. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  70268. for (var i = 0; i < this._impostors.length; ++i) {
  70269. if (this._impostors[i].object === object) {
  70270. return this._impostors[i];
  70271. }
  70272. }
  70273. return null;
  70274. };
  70275. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  70276. for (var i = 0; i < this._impostors.length; ++i) {
  70277. if (this._impostors[i].physicsBody === body) {
  70278. return this._impostors[i];
  70279. }
  70280. }
  70281. return null;
  70282. };
  70283. // Statics
  70284. PhysicsEngine.Epsilon = 0.001;
  70285. return PhysicsEngine;
  70286. }());
  70287. BABYLON.PhysicsEngine = PhysicsEngine;
  70288. })(BABYLON || (BABYLON = {}));
  70289. //# sourceMappingURL=babylon.physicsEngine.js.map
  70290. var BABYLON;
  70291. (function (BABYLON) {
  70292. var PhysicsHelper = /** @class */ (function () {
  70293. function PhysicsHelper(scene) {
  70294. this._scene = scene;
  70295. this._physicsEngine = this._scene.getPhysicsEngine();
  70296. if (!this._physicsEngine) {
  70297. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  70298. }
  70299. }
  70300. /**
  70301. * @param {Vector3} origin the origin of the explosion
  70302. * @param {number} radius the explosion radius
  70303. * @param {number} strength the explosion strength
  70304. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70305. */
  70306. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  70307. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70308. if (!this._physicsEngine) {
  70309. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  70310. return null;
  70311. }
  70312. var impostors = this._physicsEngine.getImpostors();
  70313. if (impostors.length === 0) {
  70314. return null;
  70315. }
  70316. var event = new PhysicsRadialExplosionEvent(this._scene);
  70317. impostors.forEach(function (impostor) {
  70318. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70319. if (!impostorForceAndContactPoint) {
  70320. return;
  70321. }
  70322. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70323. });
  70324. event.dispose(false);
  70325. return event;
  70326. };
  70327. /**
  70328. * @param {Vector3} origin the origin of the explosion
  70329. * @param {number} radius the explosion radius
  70330. * @param {number} strength the explosion strength
  70331. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70332. */
  70333. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  70334. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70335. if (!this._physicsEngine) {
  70336. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70337. return null;
  70338. }
  70339. var impostors = this._physicsEngine.getImpostors();
  70340. if (impostors.length === 0) {
  70341. return null;
  70342. }
  70343. var event = new PhysicsRadialExplosionEvent(this._scene);
  70344. impostors.forEach(function (impostor) {
  70345. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70346. if (!impostorForceAndContactPoint) {
  70347. return;
  70348. }
  70349. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70350. });
  70351. event.dispose(false);
  70352. return event;
  70353. };
  70354. /**
  70355. * @param {Vector3} origin the origin of the explosion
  70356. * @param {number} radius the explosion radius
  70357. * @param {number} strength the explosion strength
  70358. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70359. */
  70360. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  70361. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70362. if (!this._physicsEngine) {
  70363. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70364. return null;
  70365. }
  70366. var impostors = this._physicsEngine.getImpostors();
  70367. if (impostors.length === 0) {
  70368. return null;
  70369. }
  70370. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  70371. event.dispose(false);
  70372. return event;
  70373. };
  70374. /**
  70375. * @param {Vector3} origin the origin of the updraft
  70376. * @param {number} radius the radius of the updraft
  70377. * @param {number} strength the strength of the updraft
  70378. * @param {number} height the height of the updraft
  70379. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  70380. */
  70381. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  70382. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  70383. if (!this._physicsEngine) {
  70384. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70385. return null;
  70386. }
  70387. if (this._physicsEngine.getImpostors().length === 0) {
  70388. return null;
  70389. }
  70390. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  70391. event.dispose(false);
  70392. return event;
  70393. };
  70394. /**
  70395. * @param {Vector3} origin the of the vortex
  70396. * @param {number} radius the radius of the vortex
  70397. * @param {number} strength the strength of the vortex
  70398. * @param {number} height the height of the vortex
  70399. */
  70400. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  70401. if (!this._physicsEngine) {
  70402. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70403. return null;
  70404. }
  70405. if (this._physicsEngine.getImpostors().length === 0) {
  70406. return null;
  70407. }
  70408. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  70409. event.dispose(false);
  70410. return event;
  70411. };
  70412. return PhysicsHelper;
  70413. }());
  70414. BABYLON.PhysicsHelper = PhysicsHelper;
  70415. /***** Radial explosion *****/
  70416. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  70417. function PhysicsRadialExplosionEvent(scene) {
  70418. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  70419. this._rays = [];
  70420. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  70421. this._scene = scene;
  70422. }
  70423. /**
  70424. * Returns the data related to the radial explosion event (sphere & rays).
  70425. * @returns {PhysicsRadialExplosionEventData}
  70426. */
  70427. PhysicsRadialExplosionEvent.prototype.getData = function () {
  70428. this._dataFetched = true;
  70429. return {
  70430. sphere: this._sphere,
  70431. rays: this._rays,
  70432. };
  70433. };
  70434. /**
  70435. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  70436. * @param impostor
  70437. * @param {Vector3} origin the origin of the explosion
  70438. * @param {number} radius the explosion radius
  70439. * @param {number} strength the explosion strength
  70440. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  70441. * @returns {Nullable<PhysicsForceAndContactPoint>}
  70442. */
  70443. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  70444. if (impostor.mass === 0) {
  70445. return null;
  70446. }
  70447. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  70448. return null;
  70449. }
  70450. if (impostor.object.getClassName() !== 'Mesh') {
  70451. return null;
  70452. }
  70453. var impostorObject = impostor.object;
  70454. var impostorObjectCenter = impostor.getObjectCenter();
  70455. var direction = impostorObjectCenter.subtract(origin);
  70456. var ray = new BABYLON.Ray(origin, direction, radius);
  70457. this._rays.push(ray);
  70458. var hit = ray.intersectsMesh(impostorObject);
  70459. var contactPoint = hit.pickedPoint;
  70460. if (!contactPoint) {
  70461. return null;
  70462. }
  70463. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  70464. if (distanceFromOrigin > radius) {
  70465. return null;
  70466. }
  70467. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  70468. ? strength
  70469. : strength * (1 - (distanceFromOrigin / radius));
  70470. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70471. return { force: force, contactPoint: contactPoint };
  70472. };
  70473. /**
  70474. * Disposes the sphere.
  70475. * @param {bolean} force
  70476. */
  70477. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  70478. var _this = this;
  70479. if (force === void 0) { force = true; }
  70480. if (force) {
  70481. this._sphere.dispose();
  70482. }
  70483. else {
  70484. setTimeout(function () {
  70485. if (!_this._dataFetched) {
  70486. _this._sphere.dispose();
  70487. }
  70488. }, 0);
  70489. }
  70490. };
  70491. /*** Helpers ***/
  70492. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  70493. if (!this._sphere) {
  70494. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  70495. this._sphere.isVisible = false;
  70496. }
  70497. };
  70498. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  70499. var impostorObject = impostor.object;
  70500. this._prepareSphere();
  70501. this._sphere.position = origin;
  70502. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  70503. this._sphere._updateBoundingInfo();
  70504. this._sphere.computeWorldMatrix(true);
  70505. return this._sphere.intersectsMesh(impostorObject, true);
  70506. };
  70507. return PhysicsRadialExplosionEvent;
  70508. }());
  70509. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  70510. /***** Gravitational Field *****/
  70511. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  70512. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  70513. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70514. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70515. this._physicsHelper = physicsHelper;
  70516. this._scene = scene;
  70517. this._origin = origin;
  70518. this._radius = radius;
  70519. this._strength = strength;
  70520. this._falloff = falloff;
  70521. this._tickCallback = this._tick.bind(this);
  70522. }
  70523. /**
  70524. * Returns the data related to the gravitational field event (sphere).
  70525. * @returns {PhysicsGravitationalFieldEventData}
  70526. */
  70527. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  70528. this._dataFetched = true;
  70529. return {
  70530. sphere: this._sphere,
  70531. };
  70532. };
  70533. /**
  70534. * Enables the gravitational field.
  70535. */
  70536. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  70537. this._tickCallback.call(this);
  70538. this._scene.registerBeforeRender(this._tickCallback);
  70539. };
  70540. /**
  70541. * Disables the gravitational field.
  70542. */
  70543. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  70544. this._scene.unregisterBeforeRender(this._tickCallback);
  70545. };
  70546. /**
  70547. * Disposes the sphere.
  70548. * @param {bolean} force
  70549. */
  70550. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  70551. var _this = this;
  70552. if (force === void 0) { force = true; }
  70553. if (force) {
  70554. this._sphere.dispose();
  70555. }
  70556. else {
  70557. setTimeout(function () {
  70558. if (!_this._dataFetched) {
  70559. _this._sphere.dispose();
  70560. }
  70561. }, 0);
  70562. }
  70563. };
  70564. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  70565. // Since the params won't change, we fetch the event only once
  70566. if (this._sphere) {
  70567. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70568. }
  70569. else {
  70570. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  70571. if (radialExplosionEvent) {
  70572. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  70573. }
  70574. }
  70575. };
  70576. return PhysicsGravitationalFieldEvent;
  70577. }());
  70578. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  70579. /***** Updraft *****/
  70580. var PhysicsUpdraftEvent = /** @class */ (function () {
  70581. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  70582. this._scene = _scene;
  70583. this._origin = _origin;
  70584. this._radius = _radius;
  70585. this._strength = _strength;
  70586. this._height = _height;
  70587. this._updraftMode = _updraftMode;
  70588. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70589. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  70590. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70591. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70592. this._physicsEngine = this._scene.getPhysicsEngine();
  70593. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70594. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70595. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70596. this._originDirection = this._origin.subtract(this._originTop).normalize();
  70597. }
  70598. this._tickCallback = this._tick.bind(this);
  70599. }
  70600. /**
  70601. * Returns the data related to the updraft event (cylinder).
  70602. * @returns {PhysicsUpdraftEventData}
  70603. */
  70604. PhysicsUpdraftEvent.prototype.getData = function () {
  70605. this._dataFetched = true;
  70606. return {
  70607. cylinder: this._cylinder,
  70608. };
  70609. };
  70610. /**
  70611. * Enables the updraft.
  70612. */
  70613. PhysicsUpdraftEvent.prototype.enable = function () {
  70614. this._tickCallback.call(this);
  70615. this._scene.registerBeforeRender(this._tickCallback);
  70616. };
  70617. /**
  70618. * Disables the cortex.
  70619. */
  70620. PhysicsUpdraftEvent.prototype.disable = function () {
  70621. this._scene.unregisterBeforeRender(this._tickCallback);
  70622. };
  70623. /**
  70624. * Disposes the sphere.
  70625. * @param {bolean} force
  70626. */
  70627. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  70628. var _this = this;
  70629. if (force === void 0) { force = true; }
  70630. if (force) {
  70631. this._cylinder.dispose();
  70632. }
  70633. else {
  70634. setTimeout(function () {
  70635. if (!_this._dataFetched) {
  70636. _this._cylinder.dispose();
  70637. }
  70638. }, 0);
  70639. }
  70640. };
  70641. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70642. if (impostor.mass === 0) {
  70643. return null;
  70644. }
  70645. if (!this._intersectsWithCylinder(impostor)) {
  70646. return null;
  70647. }
  70648. var impostorObjectCenter = impostor.getObjectCenter();
  70649. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  70650. var direction = this._originDirection;
  70651. }
  70652. else {
  70653. var direction = impostorObjectCenter.subtract(this._originTop);
  70654. }
  70655. var multiplier = this._strength * -1;
  70656. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70657. return { force: force, contactPoint: impostorObjectCenter };
  70658. };
  70659. PhysicsUpdraftEvent.prototype._tick = function () {
  70660. var _this = this;
  70661. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70662. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70663. if (!impostorForceAndContactPoint) {
  70664. return;
  70665. }
  70666. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70667. });
  70668. };
  70669. /*** Helpers ***/
  70670. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  70671. if (!this._cylinder) {
  70672. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  70673. height: this._height,
  70674. diameter: this._radius * 2,
  70675. }, this._scene);
  70676. this._cylinder.isVisible = false;
  70677. }
  70678. };
  70679. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  70680. var impostorObject = impostor.object;
  70681. this._prepareCylinder();
  70682. this._cylinder.position = this._cylinderPosition;
  70683. return this._cylinder.intersectsMesh(impostorObject, true);
  70684. };
  70685. return PhysicsUpdraftEvent;
  70686. }());
  70687. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  70688. /***** Vortex *****/
  70689. var PhysicsVortexEvent = /** @class */ (function () {
  70690. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  70691. this._scene = _scene;
  70692. this._origin = _origin;
  70693. this._radius = _radius;
  70694. this._strength = _strength;
  70695. this._height = _height;
  70696. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  70697. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  70698. this._updraftMultiplier = 0.02;
  70699. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  70700. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70701. this._physicsEngine = this._scene.getPhysicsEngine();
  70702. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  70703. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  70704. this._tickCallback = this._tick.bind(this);
  70705. }
  70706. /**
  70707. * Returns the data related to the vortex event (cylinder).
  70708. * @returns {PhysicsVortexEventData}
  70709. */
  70710. PhysicsVortexEvent.prototype.getData = function () {
  70711. this._dataFetched = true;
  70712. return {
  70713. cylinder: this._cylinder,
  70714. };
  70715. };
  70716. /**
  70717. * Enables the vortex.
  70718. */
  70719. PhysicsVortexEvent.prototype.enable = function () {
  70720. this._tickCallback.call(this);
  70721. this._scene.registerBeforeRender(this._tickCallback);
  70722. };
  70723. /**
  70724. * Disables the cortex.
  70725. */
  70726. PhysicsVortexEvent.prototype.disable = function () {
  70727. this._scene.unregisterBeforeRender(this._tickCallback);
  70728. };
  70729. /**
  70730. * Disposes the sphere.
  70731. * @param {bolean} force
  70732. */
  70733. PhysicsVortexEvent.prototype.dispose = function (force) {
  70734. var _this = this;
  70735. if (force === void 0) { force = true; }
  70736. if (force) {
  70737. this._cylinder.dispose();
  70738. }
  70739. else {
  70740. setTimeout(function () {
  70741. if (!_this._dataFetched) {
  70742. _this._cylinder.dispose();
  70743. }
  70744. }, 0);
  70745. }
  70746. };
  70747. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  70748. if (impostor.mass === 0) {
  70749. return null;
  70750. }
  70751. if (!this._intersectsWithCylinder(impostor)) {
  70752. return null;
  70753. }
  70754. if (impostor.object.getClassName() !== 'Mesh') {
  70755. return null;
  70756. }
  70757. var impostorObject = impostor.object;
  70758. var impostorObjectCenter = impostor.getObjectCenter();
  70759. 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)
  70760. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  70761. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  70762. var hit = ray.intersectsMesh(impostorObject);
  70763. var contactPoint = hit.pickedPoint;
  70764. if (!contactPoint) {
  70765. return null;
  70766. }
  70767. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  70768. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  70769. var directionToOrigin = contactPoint.normalize();
  70770. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70771. directionToOrigin = directionToOrigin.negate();
  70772. }
  70773. // TODO: find a more physically based solution
  70774. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  70775. var forceX = directionToOrigin.x * this._strength / 8;
  70776. var forceY = directionToOrigin.y * this._updraftMultiplier;
  70777. var forceZ = directionToOrigin.z * this._strength / 8;
  70778. }
  70779. else {
  70780. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  70781. var forceY = this._originTop.y * this._updraftMultiplier;
  70782. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  70783. }
  70784. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  70785. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  70786. return { force: force, contactPoint: impostorObjectCenter };
  70787. };
  70788. PhysicsVortexEvent.prototype._tick = function () {
  70789. var _this = this;
  70790. this._physicsEngine.getImpostors().forEach(function (impostor) {
  70791. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  70792. if (!impostorForceAndContactPoint) {
  70793. return;
  70794. }
  70795. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70796. });
  70797. };
  70798. /*** Helpers ***/
  70799. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  70800. if (!this._cylinder) {
  70801. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  70802. height: this._height,
  70803. diameter: this._radius * 2,
  70804. }, this._scene);
  70805. this._cylinder.isVisible = false;
  70806. }
  70807. };
  70808. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  70809. var impostorObject = impostor.object;
  70810. this._prepareCylinder();
  70811. this._cylinder.position = this._cylinderPosition;
  70812. return this._cylinder.intersectsMesh(impostorObject, true);
  70813. };
  70814. return PhysicsVortexEvent;
  70815. }());
  70816. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  70817. /***** Enums *****/
  70818. /**
  70819. * The strenght of the force in correspondence to the distance of the affected object
  70820. */
  70821. var PhysicsRadialImpulseFalloff;
  70822. (function (PhysicsRadialImpulseFalloff) {
  70823. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  70824. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  70825. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  70826. /**
  70827. * The strenght of the force in correspondence to the distance of the affected object
  70828. */
  70829. var PhysicsUpdraftMode;
  70830. (function (PhysicsUpdraftMode) {
  70831. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  70832. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  70833. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  70834. })(BABYLON || (BABYLON = {}));
  70835. //# sourceMappingURL=babylon.physicsHelper.js.map
  70836. var BABYLON;
  70837. (function (BABYLON) {
  70838. var CannonJSPlugin = /** @class */ (function () {
  70839. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  70840. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  70841. if (iterations === void 0) { iterations = 10; }
  70842. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  70843. this.name = "CannonJSPlugin";
  70844. this._physicsMaterials = new Array();
  70845. this._fixedTimeStep = 1 / 60;
  70846. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  70847. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  70848. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  70849. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  70850. this._tmpPosition = BABYLON.Vector3.Zero();
  70851. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  70852. this._tmpUnityRotation = new BABYLON.Quaternion();
  70853. if (!this.isSupported()) {
  70854. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  70855. return;
  70856. }
  70857. this._extendNamespace();
  70858. this.world = new this.BJSCANNON.World();
  70859. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  70860. this.world.solver.iterations = iterations;
  70861. }
  70862. CannonJSPlugin.prototype.setGravity = function (gravity) {
  70863. this.world.gravity.copy(gravity);
  70864. };
  70865. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  70866. this._fixedTimeStep = timeStep;
  70867. };
  70868. CannonJSPlugin.prototype.getTimeStep = function () {
  70869. return this._fixedTimeStep;
  70870. };
  70871. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  70872. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  70873. };
  70874. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  70875. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  70876. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  70877. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  70878. };
  70879. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  70880. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  70881. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  70882. impostor.physicsBody.applyForce(impulse, worldPoint);
  70883. };
  70884. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  70885. //parent-child relationship. Does this impostor has a parent impostor?
  70886. if (impostor.parent) {
  70887. if (impostor.physicsBody) {
  70888. this.removePhysicsBody(impostor);
  70889. //TODO is that needed?
  70890. impostor.forceUpdate();
  70891. }
  70892. return;
  70893. }
  70894. //should a new body be created for this impostor?
  70895. if (impostor.isBodyInitRequired()) {
  70896. var shape = this._createShape(impostor);
  70897. //unregister events, if body is being changed
  70898. var oldBody = impostor.physicsBody;
  70899. if (oldBody) {
  70900. this.removePhysicsBody(impostor);
  70901. }
  70902. //create the body and material
  70903. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  70904. var bodyCreationObject = {
  70905. mass: impostor.getParam("mass"),
  70906. material: material
  70907. };
  70908. // A simple extend, in case native options were used.
  70909. var nativeOptions = impostor.getParam("nativeOptions");
  70910. for (var key in nativeOptions) {
  70911. if (nativeOptions.hasOwnProperty(key)) {
  70912. bodyCreationObject[key] = nativeOptions[key];
  70913. }
  70914. }
  70915. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  70916. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  70917. this.world.addEventListener("preStep", impostor.beforeStep);
  70918. this.world.addEventListener("postStep", impostor.afterStep);
  70919. impostor.physicsBody.addShape(shape);
  70920. this.world.add(impostor.physicsBody);
  70921. //try to keep the body moving in the right direction by taking old properties.
  70922. //Should be tested!
  70923. if (oldBody) {
  70924. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  70925. impostor.physicsBody[param].copy(oldBody[param]);
  70926. });
  70927. }
  70928. this._processChildMeshes(impostor);
  70929. }
  70930. //now update the body's transformation
  70931. this._updatePhysicsBodyTransformation(impostor);
  70932. };
  70933. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  70934. var _this = this;
  70935. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  70936. var currentRotation = mainImpostor.object.rotationQuaternion;
  70937. if (meshChildren.length) {
  70938. var processMesh = function (localPosition, mesh) {
  70939. if (!currentRotation || !mesh.rotationQuaternion) {
  70940. return;
  70941. }
  70942. var childImpostor = mesh.getPhysicsImpostor();
  70943. if (childImpostor) {
  70944. var parent = childImpostor.parent;
  70945. if (parent !== mainImpostor) {
  70946. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  70947. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  70948. if (childImpostor.physicsBody) {
  70949. _this.removePhysicsBody(childImpostor);
  70950. childImpostor.physicsBody = null;
  70951. }
  70952. childImpostor.parent = mainImpostor;
  70953. childImpostor.resetUpdateFlags();
  70954. 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));
  70955. //Add the mass of the children.
  70956. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  70957. }
  70958. }
  70959. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  70960. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  70961. };
  70962. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  70963. }
  70964. };
  70965. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  70966. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  70967. this.world.removeEventListener("preStep", impostor.beforeStep);
  70968. this.world.removeEventListener("postStep", impostor.afterStep);
  70969. this.world.remove(impostor.physicsBody);
  70970. };
  70971. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  70972. var mainBody = impostorJoint.mainImpostor.physicsBody;
  70973. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  70974. if (!mainBody || !connectedBody) {
  70975. return;
  70976. }
  70977. var constraint;
  70978. var jointData = impostorJoint.joint.jointData;
  70979. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  70980. var constraintData = {
  70981. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  70982. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  70983. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  70984. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  70985. maxForce: jointData.nativeParams.maxForce,
  70986. collideConnected: !!jointData.collision
  70987. };
  70988. switch (impostorJoint.joint.type) {
  70989. case BABYLON.PhysicsJoint.HingeJoint:
  70990. case BABYLON.PhysicsJoint.Hinge2Joint:
  70991. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  70992. break;
  70993. case BABYLON.PhysicsJoint.DistanceJoint:
  70994. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  70995. break;
  70996. case BABYLON.PhysicsJoint.SpringJoint:
  70997. var springData = jointData;
  70998. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  70999. restLength: springData.length,
  71000. stiffness: springData.stiffness,
  71001. damping: springData.damping,
  71002. localAnchorA: constraintData.pivotA,
  71003. localAnchorB: constraintData.pivotB
  71004. });
  71005. break;
  71006. case BABYLON.PhysicsJoint.LockJoint:
  71007. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71008. break;
  71009. case BABYLON.PhysicsJoint.PointToPointJoint:
  71010. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71011. default:
  71012. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71013. break;
  71014. }
  71015. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71016. constraint.collideConnected = !!jointData.collision;
  71017. impostorJoint.joint.physicsJoint = constraint;
  71018. //don't add spring as constraint, as it is not one.
  71019. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71020. this.world.addConstraint(constraint);
  71021. }
  71022. else {
  71023. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71024. constraint.applyForce();
  71025. });
  71026. }
  71027. };
  71028. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71029. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71030. };
  71031. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71032. var index;
  71033. var mat;
  71034. for (index = 0; index < this._physicsMaterials.length; index++) {
  71035. mat = this._physicsMaterials[index];
  71036. if (mat.friction === friction && mat.restitution === restitution) {
  71037. return mat;
  71038. }
  71039. }
  71040. var currentMat = new this.BJSCANNON.Material(name);
  71041. currentMat.friction = friction;
  71042. currentMat.restitution = restitution;
  71043. this._physicsMaterials.push(currentMat);
  71044. return currentMat;
  71045. };
  71046. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71047. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71048. };
  71049. CannonJSPlugin.prototype._createShape = function (impostor) {
  71050. var object = impostor.object;
  71051. var returnValue;
  71052. var extendSize = impostor.getObjectExtendSize();
  71053. switch (impostor.type) {
  71054. case BABYLON.PhysicsImpostor.SphereImpostor:
  71055. var radiusX = extendSize.x;
  71056. var radiusY = extendSize.y;
  71057. var radiusZ = extendSize.z;
  71058. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71059. break;
  71060. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71061. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71062. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71063. break;
  71064. case BABYLON.PhysicsImpostor.BoxImpostor:
  71065. var box = extendSize.scale(0.5);
  71066. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71067. break;
  71068. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71069. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71070. returnValue = new this.BJSCANNON.Plane();
  71071. break;
  71072. case BABYLON.PhysicsImpostor.MeshImpostor:
  71073. // should transform the vertex data to world coordinates!!
  71074. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71075. var rawFaces = object.getIndices ? object.getIndices() : [];
  71076. if (!rawVerts)
  71077. return;
  71078. // get only scale! so the object could transform correctly.
  71079. var oldPosition = object.position.clone();
  71080. var oldRotation = object.rotation && object.rotation.clone();
  71081. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71082. object.position.copyFromFloats(0, 0, 0);
  71083. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71084. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71085. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71086. var transform = object.computeWorldMatrix(true);
  71087. // convert rawVerts to object space
  71088. var temp = new Array();
  71089. var index;
  71090. for (index = 0; index < rawVerts.length; index += 3) {
  71091. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71092. }
  71093. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71094. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71095. //now set back the transformation!
  71096. object.position.copyFrom(oldPosition);
  71097. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71098. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71099. break;
  71100. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71101. var oldPosition2 = object.position.clone();
  71102. var oldRotation2 = object.rotation && object.rotation.clone();
  71103. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71104. object.position.copyFromFloats(0, 0, 0);
  71105. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71106. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71107. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71108. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71109. returnValue = this._createHeightmap(object);
  71110. object.position.copyFrom(oldPosition2);
  71111. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71112. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71113. object.computeWorldMatrix(true);
  71114. break;
  71115. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71116. returnValue = new this.BJSCANNON.Particle();
  71117. break;
  71118. }
  71119. return returnValue;
  71120. };
  71121. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71122. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71123. var transform = object.computeWorldMatrix(true);
  71124. // convert rawVerts to object space
  71125. var temp = new Array();
  71126. var index;
  71127. for (index = 0; index < pos.length; index += 3) {
  71128. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71129. }
  71130. pos = temp;
  71131. var matrix = new Array();
  71132. //For now pointDepth will not be used and will be automatically calculated.
  71133. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71134. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71135. var boundingInfo = object.getBoundingInfo();
  71136. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71137. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71138. var elementSize = dim * 2 / arraySize;
  71139. for (var i = 0; i < pos.length; i = i + 3) {
  71140. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71141. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71142. var y = -pos[i + 2] + minY;
  71143. if (!matrix[x]) {
  71144. matrix[x] = [];
  71145. }
  71146. if (!matrix[x][z]) {
  71147. matrix[x][z] = y;
  71148. }
  71149. matrix[x][z] = Math.max(y, matrix[x][z]);
  71150. }
  71151. for (var x = 0; x <= arraySize; ++x) {
  71152. if (!matrix[x]) {
  71153. var loc = 1;
  71154. while (!matrix[(x + loc) % arraySize]) {
  71155. loc++;
  71156. }
  71157. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71158. //console.log("missing x", x);
  71159. }
  71160. for (var z = 0; z <= arraySize; ++z) {
  71161. if (!matrix[x][z]) {
  71162. var loc = 1;
  71163. var newValue;
  71164. while (newValue === undefined) {
  71165. newValue = matrix[x][(z + loc++) % arraySize];
  71166. }
  71167. matrix[x][z] = newValue;
  71168. }
  71169. }
  71170. }
  71171. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71172. elementSize: elementSize
  71173. });
  71174. //For future reference, needed for body transformation
  71175. shape.minY = minY;
  71176. return shape;
  71177. };
  71178. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71179. var object = impostor.object;
  71180. //make sure it is updated...
  71181. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71182. // The delta between the mesh position and the mesh bounding box center
  71183. var bInfo = object.getBoundingInfo();
  71184. if (!bInfo)
  71185. return;
  71186. var center = impostor.getObjectCenter();
  71187. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71188. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71189. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71190. this._tmpPosition.copyFrom(center);
  71191. var quaternion = object.rotationQuaternion;
  71192. if (!quaternion) {
  71193. return;
  71194. }
  71195. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71196. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71197. //-90 DEG in X, precalculated
  71198. quaternion = quaternion.multiply(this._minus90X);
  71199. //Invert! (Precalculated, 90 deg in X)
  71200. //No need to clone. this will never change.
  71201. impostor.setDeltaRotation(this._plus90X);
  71202. }
  71203. //If it is a heightfield, if should be centered.
  71204. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71205. var mesh = object;
  71206. var boundingInfo = mesh.getBoundingInfo();
  71207. //calculate the correct body position:
  71208. var rotationQuaternion = mesh.rotationQuaternion;
  71209. mesh.rotationQuaternion = this._tmpUnityRotation;
  71210. mesh.computeWorldMatrix(true);
  71211. //get original center with no rotation
  71212. var c = center.clone();
  71213. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71214. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71215. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71216. mesh.setPivotMatrix(p);
  71217. mesh.computeWorldMatrix(true);
  71218. //calculate the translation
  71219. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71220. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71221. //add it inverted to the delta
  71222. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71223. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71224. //rotation is back
  71225. mesh.rotationQuaternion = rotationQuaternion;
  71226. mesh.setPivotMatrix(oldPivot);
  71227. mesh.computeWorldMatrix(true);
  71228. }
  71229. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71230. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71231. //this._tmpPosition.copyFrom(object.position);
  71232. }
  71233. impostor.setDeltaPosition(this._tmpDeltaPosition);
  71234. //Now update the impostor object
  71235. impostor.physicsBody.position.copy(this._tmpPosition);
  71236. impostor.physicsBody.quaternion.copy(quaternion);
  71237. };
  71238. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71239. impostor.object.position.copyFrom(impostor.physicsBody.position);
  71240. if (impostor.object.rotationQuaternion) {
  71241. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  71242. }
  71243. };
  71244. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71245. impostor.physicsBody.position.copy(newPosition);
  71246. impostor.physicsBody.quaternion.copy(newRotation);
  71247. };
  71248. CannonJSPlugin.prototype.isSupported = function () {
  71249. return this.BJSCANNON !== undefined;
  71250. };
  71251. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71252. impostor.physicsBody.velocity.copy(velocity);
  71253. };
  71254. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71255. impostor.physicsBody.angularVelocity.copy(velocity);
  71256. };
  71257. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71258. var v = impostor.physicsBody.velocity;
  71259. if (!v) {
  71260. return null;
  71261. }
  71262. return new BABYLON.Vector3(v.x, v.y, v.z);
  71263. };
  71264. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71265. var v = impostor.physicsBody.angularVelocity;
  71266. if (!v) {
  71267. return null;
  71268. }
  71269. return new BABYLON.Vector3(v.x, v.y, v.z);
  71270. };
  71271. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71272. impostor.physicsBody.mass = mass;
  71273. impostor.physicsBody.updateMassProperties();
  71274. };
  71275. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  71276. return impostor.physicsBody.mass;
  71277. };
  71278. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  71279. return impostor.physicsBody.material.friction;
  71280. };
  71281. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71282. impostor.physicsBody.material.friction = friction;
  71283. };
  71284. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71285. return impostor.physicsBody.material.restitution;
  71286. };
  71287. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71288. impostor.physicsBody.material.restitution = restitution;
  71289. };
  71290. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  71291. impostor.physicsBody.sleep();
  71292. };
  71293. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  71294. impostor.physicsBody.wakeUp();
  71295. };
  71296. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71297. joint.physicsJoint.distance = maxDistance;
  71298. };
  71299. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71300. // if (!motorIndex) {
  71301. // joint.physicsJoint.enableMotor();
  71302. // }
  71303. // }
  71304. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71305. // if (!motorIndex) {
  71306. // joint.physicsJoint.disableMotor();
  71307. // }
  71308. // }
  71309. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71310. if (!motorIndex) {
  71311. joint.physicsJoint.enableMotor();
  71312. joint.physicsJoint.setMotorSpeed(speed);
  71313. if (maxForce) {
  71314. this.setLimit(joint, maxForce);
  71315. }
  71316. }
  71317. };
  71318. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  71319. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  71320. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  71321. };
  71322. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71323. var body = impostor.physicsBody;
  71324. mesh.position.x = body.position.x;
  71325. mesh.position.y = body.position.y;
  71326. mesh.position.z = body.position.z;
  71327. if (mesh.rotationQuaternion) {
  71328. mesh.rotationQuaternion.x = body.quaternion.x;
  71329. mesh.rotationQuaternion.y = body.quaternion.y;
  71330. mesh.rotationQuaternion.z = body.quaternion.z;
  71331. mesh.rotationQuaternion.w = body.quaternion.w;
  71332. }
  71333. };
  71334. CannonJSPlugin.prototype.getRadius = function (impostor) {
  71335. var shape = impostor.physicsBody.shapes[0];
  71336. return shape.boundingSphereRadius;
  71337. };
  71338. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71339. var shape = impostor.physicsBody.shapes[0];
  71340. result.x = shape.halfExtents.x * 2;
  71341. result.y = shape.halfExtents.y * 2;
  71342. result.z = shape.halfExtents.z * 2;
  71343. };
  71344. CannonJSPlugin.prototype.dispose = function () {
  71345. };
  71346. CannonJSPlugin.prototype._extendNamespace = function () {
  71347. //this will force cannon to execute at least one step when using interpolation
  71348. var step_tmp1 = new this.BJSCANNON.Vec3();
  71349. var Engine = this.BJSCANNON;
  71350. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  71351. maxSubSteps = maxSubSteps || 10;
  71352. timeSinceLastCalled = timeSinceLastCalled || 0;
  71353. if (timeSinceLastCalled === 0) {
  71354. this.internalStep(dt);
  71355. this.time += dt;
  71356. }
  71357. else {
  71358. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  71359. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  71360. var t0 = performance.now();
  71361. for (var i = 0; i !== internalSteps; i++) {
  71362. this.internalStep(dt);
  71363. if (performance.now() - t0 > dt * 1000) {
  71364. break;
  71365. }
  71366. }
  71367. this.time += timeSinceLastCalled;
  71368. var h = this.time % dt;
  71369. var h_div_dt = h / dt;
  71370. var interpvelo = step_tmp1;
  71371. var bodies = this.bodies;
  71372. for (var j = 0; j !== bodies.length; j++) {
  71373. var b = bodies[j];
  71374. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  71375. b.position.vsub(b.previousPosition, interpvelo);
  71376. interpvelo.scale(h_div_dt, interpvelo);
  71377. b.position.vadd(interpvelo, b.interpolatedPosition);
  71378. }
  71379. else {
  71380. b.interpolatedPosition.copy(b.position);
  71381. b.interpolatedQuaternion.copy(b.quaternion);
  71382. }
  71383. }
  71384. }
  71385. };
  71386. };
  71387. return CannonJSPlugin;
  71388. }());
  71389. BABYLON.CannonJSPlugin = CannonJSPlugin;
  71390. })(BABYLON || (BABYLON = {}));
  71391. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  71392. var BABYLON;
  71393. (function (BABYLON) {
  71394. var OimoJSPlugin = /** @class */ (function () {
  71395. function OimoJSPlugin(iterations) {
  71396. this.name = "OimoJSPlugin";
  71397. this._tmpImpostorsArray = [];
  71398. this._tmpPositionVector = BABYLON.Vector3.Zero();
  71399. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  71400. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  71401. this.world.worldscale(1);
  71402. this.world.clear();
  71403. //making sure no stats are calculated
  71404. this.world.isNoStat = true;
  71405. }
  71406. OimoJSPlugin.prototype.setGravity = function (gravity) {
  71407. this.world.gravity.copy(gravity);
  71408. };
  71409. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  71410. this.world.timeStep = timeStep;
  71411. };
  71412. OimoJSPlugin.prototype.getTimeStep = function () {
  71413. return this.world.timeStep;
  71414. };
  71415. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  71416. var _this = this;
  71417. impostors.forEach(function (impostor) {
  71418. impostor.beforeStep();
  71419. });
  71420. this.world.step();
  71421. impostors.forEach(function (impostor) {
  71422. impostor.afterStep();
  71423. //update the ordered impostors array
  71424. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  71425. });
  71426. //check for collisions
  71427. var contact = this.world.contacts;
  71428. while (contact !== null) {
  71429. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  71430. contact = contact.next;
  71431. continue;
  71432. }
  71433. //is this body colliding with any other? get the impostor
  71434. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  71435. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  71436. if (!mainImpostor || !collidingImpostor) {
  71437. contact = contact.next;
  71438. continue;
  71439. }
  71440. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  71441. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  71442. contact = contact.next;
  71443. }
  71444. };
  71445. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71446. var mass = impostor.physicsBody.massInfo.mass;
  71447. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  71448. };
  71449. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71450. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  71451. this.applyImpulse(impostor, force, contactPoint);
  71452. };
  71453. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71454. var _this = this;
  71455. //parent-child relationship. Does this impostor has a parent impostor?
  71456. if (impostor.parent) {
  71457. if (impostor.physicsBody) {
  71458. this.removePhysicsBody(impostor);
  71459. //TODO is that needed?
  71460. impostor.forceUpdate();
  71461. }
  71462. return;
  71463. }
  71464. if (impostor.isBodyInitRequired()) {
  71465. var bodyConfig = {
  71466. name: impostor.uniqueId,
  71467. //Oimo must have mass, also for static objects.
  71468. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  71469. size: [],
  71470. type: [],
  71471. pos: [],
  71472. rot: [],
  71473. move: impostor.getParam("mass") !== 0,
  71474. //Supporting older versions of Oimo
  71475. world: this.world
  71476. };
  71477. var impostors = [impostor];
  71478. var addToArray = function (parent) {
  71479. if (!parent.getChildMeshes)
  71480. return;
  71481. parent.getChildMeshes().forEach(function (m) {
  71482. if (m.physicsImpostor) {
  71483. impostors.push(m.physicsImpostor);
  71484. //m.physicsImpostor._init();
  71485. }
  71486. });
  71487. };
  71488. addToArray(impostor.object);
  71489. var checkWithEpsilon_1 = function (value) {
  71490. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  71491. };
  71492. impostors.forEach(function (i) {
  71493. if (!impostor.object.rotationQuaternion) {
  71494. return;
  71495. }
  71496. //get the correct bounding box
  71497. var oldQuaternion = i.object.rotationQuaternion;
  71498. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  71499. x: impostor.object.rotationQuaternion.x,
  71500. y: impostor.object.rotationQuaternion.y,
  71501. z: impostor.object.rotationQuaternion.z,
  71502. s: impostor.object.rotationQuaternion.w
  71503. });
  71504. var extendSize = i.getObjectExtendSize();
  71505. if (i === impostor) {
  71506. var center = impostor.getObjectCenter();
  71507. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  71508. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  71509. //Can also use Array.prototype.push.apply
  71510. bodyConfig.pos.push(center.x);
  71511. bodyConfig.pos.push(center.y);
  71512. bodyConfig.pos.push(center.z);
  71513. //tmp solution
  71514. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71515. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71516. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71517. }
  71518. else {
  71519. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  71520. bodyConfig.pos.push(localPosition.x);
  71521. bodyConfig.pos.push(localPosition.y);
  71522. bodyConfig.pos.push(localPosition.z);
  71523. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  71524. bodyConfig.rot.push(0);
  71525. bodyConfig.rot.push(0);
  71526. bodyConfig.rot.push(0);
  71527. }
  71528. // register mesh
  71529. switch (i.type) {
  71530. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71531. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  71532. case BABYLON.PhysicsImpostor.SphereImpostor:
  71533. var radiusX = extendSize.x;
  71534. var radiusY = extendSize.y;
  71535. var radiusZ = extendSize.z;
  71536. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  71537. bodyConfig.type.push('sphere');
  71538. //due to the way oimo works with compounds, add 3 times
  71539. bodyConfig.size.push(size);
  71540. bodyConfig.size.push(size);
  71541. bodyConfig.size.push(size);
  71542. break;
  71543. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71544. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  71545. var sizeY = checkWithEpsilon_1(extendSize.y);
  71546. bodyConfig.type.push('cylinder');
  71547. bodyConfig.size.push(sizeX);
  71548. bodyConfig.size.push(sizeY);
  71549. //due to the way oimo works with compounds, add one more value.
  71550. bodyConfig.size.push(sizeY);
  71551. break;
  71552. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71553. case BABYLON.PhysicsImpostor.BoxImpostor:
  71554. default:
  71555. var sizeX = checkWithEpsilon_1(extendSize.x);
  71556. var sizeY = checkWithEpsilon_1(extendSize.y);
  71557. var sizeZ = checkWithEpsilon_1(extendSize.z);
  71558. bodyConfig.type.push('box');
  71559. bodyConfig.size.push(sizeX);
  71560. bodyConfig.size.push(sizeY);
  71561. bodyConfig.size.push(sizeZ);
  71562. break;
  71563. }
  71564. //actually not needed, but hey...
  71565. i.object.rotationQuaternion = oldQuaternion;
  71566. });
  71567. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  71568. }
  71569. else {
  71570. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  71571. }
  71572. impostor.setDeltaPosition(this._tmpPositionVector);
  71573. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  71574. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  71575. };
  71576. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71577. //impostor.physicsBody.dispose();
  71578. //Same as : (older oimo versions)
  71579. this.world.removeRigidBody(impostor.physicsBody);
  71580. };
  71581. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71582. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71583. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71584. if (!mainBody || !connectedBody) {
  71585. return;
  71586. }
  71587. var jointData = impostorJoint.joint.jointData;
  71588. var options = jointData.nativeParams || {};
  71589. var type;
  71590. var nativeJointData = {
  71591. body1: mainBody,
  71592. body2: connectedBody,
  71593. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  71594. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  71595. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  71596. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  71597. min: options.min,
  71598. max: options.max,
  71599. collision: options.collision || jointData.collision,
  71600. spring: options.spring,
  71601. //supporting older version of Oimo
  71602. world: this.world
  71603. };
  71604. switch (impostorJoint.joint.type) {
  71605. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71606. type = "jointBall";
  71607. break;
  71608. case BABYLON.PhysicsJoint.SpringJoint:
  71609. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  71610. var springData = jointData;
  71611. nativeJointData.min = springData.length || nativeJointData.min;
  71612. //Max should also be set, just make sure it is at least min
  71613. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  71614. case BABYLON.PhysicsJoint.DistanceJoint:
  71615. type = "jointDistance";
  71616. nativeJointData.max = jointData.maxDistance;
  71617. break;
  71618. case BABYLON.PhysicsJoint.PrismaticJoint:
  71619. type = "jointPrisme";
  71620. break;
  71621. case BABYLON.PhysicsJoint.SliderJoint:
  71622. type = "jointSlide";
  71623. break;
  71624. case BABYLON.PhysicsJoint.WheelJoint:
  71625. type = "jointWheel";
  71626. break;
  71627. case BABYLON.PhysicsJoint.HingeJoint:
  71628. default:
  71629. type = "jointHinge";
  71630. break;
  71631. }
  71632. nativeJointData.type = type;
  71633. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  71634. };
  71635. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71636. //Bug in Oimo prevents us from disposing a joint in the playground
  71637. //joint.joint.physicsJoint.dispose();
  71638. //So we will bruteforce it!
  71639. try {
  71640. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  71641. }
  71642. catch (e) {
  71643. BABYLON.Tools.Warn(e);
  71644. }
  71645. };
  71646. OimoJSPlugin.prototype.isSupported = function () {
  71647. return this.BJSOIMO !== undefined;
  71648. };
  71649. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71650. if (!impostor.physicsBody.sleeping) {
  71651. //TODO check that
  71652. if (impostor.physicsBody.shapes.next) {
  71653. var parentShape = this._getLastShape(impostor.physicsBody);
  71654. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  71655. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  71656. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  71657. }
  71658. else {
  71659. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  71660. }
  71661. if (impostor.object.rotationQuaternion) {
  71662. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  71663. impostor.object.rotationQuaternion.normalize();
  71664. }
  71665. }
  71666. };
  71667. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71668. var body = impostor.physicsBody;
  71669. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  71670. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  71671. body.syncShapes();
  71672. body.awake();
  71673. };
  71674. OimoJSPlugin.prototype._getLastShape = function (body) {
  71675. var lastShape = body.shapes;
  71676. while (lastShape.next) {
  71677. lastShape = lastShape.next;
  71678. }
  71679. return lastShape;
  71680. };
  71681. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71682. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  71683. };
  71684. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71685. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  71686. };
  71687. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71688. var v = impostor.physicsBody.linearVelocity;
  71689. if (!v) {
  71690. return null;
  71691. }
  71692. return new BABYLON.Vector3(v.x, v.y, v.z);
  71693. };
  71694. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71695. var v = impostor.physicsBody.angularVelocity;
  71696. if (!v) {
  71697. return null;
  71698. }
  71699. return new BABYLON.Vector3(v.x, v.y, v.z);
  71700. };
  71701. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71702. var staticBody = mass === 0;
  71703. //this will actually set the body's density and not its mass.
  71704. //But this is how oimo treats the mass variable.
  71705. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  71706. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  71707. };
  71708. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  71709. return impostor.physicsBody.shapes.density;
  71710. };
  71711. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  71712. return impostor.physicsBody.shapes.friction;
  71713. };
  71714. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71715. impostor.physicsBody.shapes.friction = friction;
  71716. };
  71717. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71718. return impostor.physicsBody.shapes.restitution;
  71719. };
  71720. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71721. impostor.physicsBody.shapes.restitution = restitution;
  71722. };
  71723. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  71724. impostor.physicsBody.sleep();
  71725. };
  71726. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  71727. impostor.physicsBody.awake();
  71728. };
  71729. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71730. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  71731. if (minDistance !== void 0) {
  71732. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  71733. }
  71734. };
  71735. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71736. //TODO separate rotational and transational motors.
  71737. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71738. if (motor) {
  71739. motor.setMotor(speed, maxForce);
  71740. }
  71741. };
  71742. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  71743. //TODO separate rotational and transational motors.
  71744. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  71745. if (motor) {
  71746. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  71747. }
  71748. };
  71749. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71750. var body = impostor.physicsBody;
  71751. mesh.position.x = body.position.x;
  71752. mesh.position.y = body.position.y;
  71753. mesh.position.z = body.position.z;
  71754. if (mesh.rotationQuaternion) {
  71755. mesh.rotationQuaternion.x = body.orientation.x;
  71756. mesh.rotationQuaternion.y = body.orientation.y;
  71757. mesh.rotationQuaternion.z = body.orientation.z;
  71758. mesh.rotationQuaternion.w = body.orientation.s;
  71759. }
  71760. };
  71761. OimoJSPlugin.prototype.getRadius = function (impostor) {
  71762. return impostor.physicsBody.shapes.radius;
  71763. };
  71764. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71765. var shape = impostor.physicsBody.shapes;
  71766. result.x = shape.halfWidth * 2;
  71767. result.y = shape.halfHeight * 2;
  71768. result.z = shape.halfDepth * 2;
  71769. };
  71770. OimoJSPlugin.prototype.dispose = function () {
  71771. this.world.clear();
  71772. };
  71773. return OimoJSPlugin;
  71774. }());
  71775. BABYLON.OimoJSPlugin = OimoJSPlugin;
  71776. })(BABYLON || (BABYLON = {}));
  71777. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  71778. var BABYLON;
  71779. (function (BABYLON) {
  71780. /*
  71781. * Based on jsTGALoader - Javascript loader for TGA file
  71782. * By Vincent Thibault
  71783. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  71784. */
  71785. var TGATools = /** @class */ (function () {
  71786. function TGATools() {
  71787. }
  71788. TGATools.GetTGAHeader = function (data) {
  71789. var offset = 0;
  71790. var header = {
  71791. id_length: data[offset++],
  71792. colormap_type: data[offset++],
  71793. image_type: data[offset++],
  71794. colormap_index: data[offset++] | data[offset++] << 8,
  71795. colormap_length: data[offset++] | data[offset++] << 8,
  71796. colormap_size: data[offset++],
  71797. origin: [
  71798. data[offset++] | data[offset++] << 8,
  71799. data[offset++] | data[offset++] << 8
  71800. ],
  71801. width: data[offset++] | data[offset++] << 8,
  71802. height: data[offset++] | data[offset++] << 8,
  71803. pixel_size: data[offset++],
  71804. flags: data[offset++]
  71805. };
  71806. return header;
  71807. };
  71808. TGATools.UploadContent = function (gl, data) {
  71809. // Not enough data to contain header ?
  71810. if (data.length < 19) {
  71811. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  71812. return;
  71813. }
  71814. // Read Header
  71815. var offset = 18;
  71816. var header = TGATools.GetTGAHeader(data);
  71817. // Assume it's a valid Targa file.
  71818. if (header.id_length + offset > data.length) {
  71819. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  71820. return;
  71821. }
  71822. // Skip not needed data
  71823. offset += header.id_length;
  71824. var use_rle = false;
  71825. var use_pal = false;
  71826. var use_grey = false;
  71827. // Get some informations.
  71828. switch (header.image_type) {
  71829. case TGATools._TYPE_RLE_INDEXED:
  71830. use_rle = true;
  71831. case TGATools._TYPE_INDEXED:
  71832. use_pal = true;
  71833. break;
  71834. case TGATools._TYPE_RLE_RGB:
  71835. use_rle = true;
  71836. case TGATools._TYPE_RGB:
  71837. // use_rgb = true;
  71838. break;
  71839. case TGATools._TYPE_RLE_GREY:
  71840. use_rle = true;
  71841. case TGATools._TYPE_GREY:
  71842. use_grey = true;
  71843. break;
  71844. }
  71845. var pixel_data;
  71846. // var numAlphaBits = header.flags & 0xf;
  71847. var pixel_size = header.pixel_size >> 3;
  71848. var pixel_total = header.width * header.height * pixel_size;
  71849. // Read palettes
  71850. var palettes;
  71851. if (use_pal) {
  71852. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  71853. }
  71854. // Read LRE
  71855. if (use_rle) {
  71856. pixel_data = new Uint8Array(pixel_total);
  71857. var c, count, i;
  71858. var localOffset = 0;
  71859. var pixels = new Uint8Array(pixel_size);
  71860. while (offset < pixel_total && localOffset < pixel_total) {
  71861. c = data[offset++];
  71862. count = (c & 0x7f) + 1;
  71863. // RLE pixels
  71864. if (c & 0x80) {
  71865. // Bind pixel tmp array
  71866. for (i = 0; i < pixel_size; ++i) {
  71867. pixels[i] = data[offset++];
  71868. }
  71869. // Copy pixel array
  71870. for (i = 0; i < count; ++i) {
  71871. pixel_data.set(pixels, localOffset + i * pixel_size);
  71872. }
  71873. localOffset += pixel_size * count;
  71874. }
  71875. else {
  71876. count *= pixel_size;
  71877. for (i = 0; i < count; ++i) {
  71878. pixel_data[localOffset + i] = data[offset++];
  71879. }
  71880. localOffset += count;
  71881. }
  71882. }
  71883. }
  71884. else {
  71885. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  71886. }
  71887. // Load to texture
  71888. var x_start, y_start, x_step, y_step, y_end, x_end;
  71889. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  71890. default:
  71891. case TGATools._ORIGIN_UL:
  71892. x_start = 0;
  71893. x_step = 1;
  71894. x_end = header.width;
  71895. y_start = 0;
  71896. y_step = 1;
  71897. y_end = header.height;
  71898. break;
  71899. case TGATools._ORIGIN_BL:
  71900. x_start = 0;
  71901. x_step = 1;
  71902. x_end = header.width;
  71903. y_start = header.height - 1;
  71904. y_step = -1;
  71905. y_end = -1;
  71906. break;
  71907. case TGATools._ORIGIN_UR:
  71908. x_start = header.width - 1;
  71909. x_step = -1;
  71910. x_end = -1;
  71911. y_start = 0;
  71912. y_step = 1;
  71913. y_end = header.height;
  71914. break;
  71915. case TGATools._ORIGIN_BR:
  71916. x_start = header.width - 1;
  71917. x_step = -1;
  71918. x_end = -1;
  71919. y_start = header.height - 1;
  71920. y_step = -1;
  71921. y_end = -1;
  71922. break;
  71923. }
  71924. // Load the specify method
  71925. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  71926. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  71927. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  71928. };
  71929. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71930. var image = pixel_data, colormap = palettes;
  71931. var width = header.width, height = header.height;
  71932. var color, i = 0, x, y;
  71933. var imageData = new Uint8Array(width * height * 4);
  71934. for (y = y_start; y !== y_end; y += y_step) {
  71935. for (x = x_start; x !== x_end; x += x_step, i++) {
  71936. color = image[i];
  71937. imageData[(x + width * y) * 4 + 3] = 255;
  71938. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  71939. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  71940. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  71941. }
  71942. }
  71943. return imageData;
  71944. };
  71945. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71946. var image = pixel_data;
  71947. var width = header.width, height = header.height;
  71948. var color, i = 0, x, y;
  71949. var imageData = new Uint8Array(width * height * 4);
  71950. for (y = y_start; y !== y_end; y += y_step) {
  71951. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  71952. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  71953. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  71954. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  71955. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  71956. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  71957. }
  71958. }
  71959. return imageData;
  71960. };
  71961. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71962. var image = pixel_data;
  71963. var width = header.width, height = header.height;
  71964. var i = 0, x, y;
  71965. var imageData = new Uint8Array(width * height * 4);
  71966. for (y = y_start; y !== y_end; y += y_step) {
  71967. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  71968. imageData[(x + width * y) * 4 + 3] = 255;
  71969. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  71970. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  71971. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  71972. }
  71973. }
  71974. return imageData;
  71975. };
  71976. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71977. var image = pixel_data;
  71978. var width = header.width, height = header.height;
  71979. var i = 0, x, y;
  71980. var imageData = new Uint8Array(width * height * 4);
  71981. for (y = y_start; y !== y_end; y += y_step) {
  71982. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  71983. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  71984. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  71985. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  71986. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  71987. }
  71988. }
  71989. return imageData;
  71990. };
  71991. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  71992. var image = pixel_data;
  71993. var width = header.width, height = header.height;
  71994. var color, i = 0, x, y;
  71995. var imageData = new Uint8Array(width * height * 4);
  71996. for (y = y_start; y !== y_end; y += y_step) {
  71997. for (x = x_start; x !== x_end; x += x_step, i++) {
  71998. color = image[i];
  71999. imageData[(x + width * y) * 4 + 0] = color;
  72000. imageData[(x + width * y) * 4 + 1] = color;
  72001. imageData[(x + width * y) * 4 + 2] = color;
  72002. imageData[(x + width * y) * 4 + 3] = 255;
  72003. }
  72004. }
  72005. return imageData;
  72006. };
  72007. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72008. var image = pixel_data;
  72009. var width = header.width, height = header.height;
  72010. var i = 0, x, y;
  72011. var imageData = new Uint8Array(width * height * 4);
  72012. for (y = y_start; y !== y_end; y += y_step) {
  72013. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72014. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72015. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72016. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72017. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72018. }
  72019. }
  72020. return imageData;
  72021. };
  72022. //private static _TYPE_NO_DATA = 0;
  72023. TGATools._TYPE_INDEXED = 1;
  72024. TGATools._TYPE_RGB = 2;
  72025. TGATools._TYPE_GREY = 3;
  72026. TGATools._TYPE_RLE_INDEXED = 9;
  72027. TGATools._TYPE_RLE_RGB = 10;
  72028. TGATools._TYPE_RLE_GREY = 11;
  72029. TGATools._ORIGIN_MASK = 0x30;
  72030. TGATools._ORIGIN_SHIFT = 0x04;
  72031. TGATools._ORIGIN_BL = 0x00;
  72032. TGATools._ORIGIN_BR = 0x01;
  72033. TGATools._ORIGIN_UL = 0x02;
  72034. TGATools._ORIGIN_UR = 0x03;
  72035. return TGATools;
  72036. }());
  72037. BABYLON.TGATools = TGATools;
  72038. })(BABYLON || (BABYLON = {}));
  72039. //# sourceMappingURL=babylon.tga.js.map
  72040. var BABYLON;
  72041. (function (BABYLON) {
  72042. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72043. // All values and structures referenced from:
  72044. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72045. var DDS_MAGIC = 0x20534444;
  72046. var
  72047. //DDSD_CAPS = 0x1,
  72048. //DDSD_HEIGHT = 0x2,
  72049. //DDSD_WIDTH = 0x4,
  72050. //DDSD_PITCH = 0x8,
  72051. //DDSD_PIXELFORMAT = 0x1000,
  72052. DDSD_MIPMAPCOUNT = 0x20000;
  72053. //DDSD_LINEARSIZE = 0x80000,
  72054. //DDSD_DEPTH = 0x800000;
  72055. // var DDSCAPS_COMPLEX = 0x8,
  72056. // DDSCAPS_MIPMAP = 0x400000,
  72057. // DDSCAPS_TEXTURE = 0x1000;
  72058. var DDSCAPS2_CUBEMAP = 0x200;
  72059. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72060. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72061. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72062. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72063. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72064. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72065. // DDSCAPS2_VOLUME = 0x200000;
  72066. var
  72067. //DDPF_ALPHAPIXELS = 0x1,
  72068. //DDPF_ALPHA = 0x2,
  72069. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72070. //DDPF_YUV = 0x200,
  72071. DDPF_LUMINANCE = 0x20000;
  72072. function FourCCToInt32(value) {
  72073. return value.charCodeAt(0) +
  72074. (value.charCodeAt(1) << 8) +
  72075. (value.charCodeAt(2) << 16) +
  72076. (value.charCodeAt(3) << 24);
  72077. }
  72078. function Int32ToFourCC(value) {
  72079. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72080. }
  72081. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72082. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72083. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72084. var FOURCC_DX10 = FourCCToInt32("DX10");
  72085. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72086. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72087. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72088. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72089. var headerLengthInt = 31; // The header length in 32 bit ints
  72090. // Offsets into the header array
  72091. var off_magic = 0;
  72092. var off_size = 1;
  72093. var off_flags = 2;
  72094. var off_height = 3;
  72095. var off_width = 4;
  72096. var off_mipmapCount = 7;
  72097. var off_pfFlags = 20;
  72098. var off_pfFourCC = 21;
  72099. var off_RGBbpp = 22;
  72100. var off_RMask = 23;
  72101. var off_GMask = 24;
  72102. var off_BMask = 25;
  72103. var off_AMask = 26;
  72104. // var off_caps1 = 27;
  72105. var off_caps2 = 28;
  72106. // var off_caps3 = 29;
  72107. // var off_caps4 = 30;
  72108. var off_dxgiFormat = 32;
  72109. ;
  72110. var DDSTools = /** @class */ (function () {
  72111. function DDSTools() {
  72112. }
  72113. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72114. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72115. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72116. var mipmapCount = 1;
  72117. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72118. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72119. }
  72120. var fourCC = header[off_pfFourCC];
  72121. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72122. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72123. switch (fourCC) {
  72124. case FOURCC_D3DFMT_R16G16B16A16F:
  72125. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72126. break;
  72127. case FOURCC_D3DFMT_R32G32B32A32F:
  72128. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72129. break;
  72130. case FOURCC_DX10:
  72131. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72132. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72133. break;
  72134. }
  72135. }
  72136. return {
  72137. width: header[off_width],
  72138. height: header[off_height],
  72139. mipmapCount: mipmapCount,
  72140. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72141. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72142. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72143. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72144. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72145. dxgiFormat: dxgiFormat,
  72146. textureType: textureType
  72147. };
  72148. };
  72149. DDSTools._ToHalfFloat = function (value) {
  72150. if (!DDSTools._FloatView) {
  72151. DDSTools._FloatView = new Float32Array(1);
  72152. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72153. }
  72154. DDSTools._FloatView[0] = value;
  72155. var x = DDSTools._Int32View[0];
  72156. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72157. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72158. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72159. /* If zero, or denormal, or exponent underflows too much for a denormal
  72160. * half, return signed zero. */
  72161. if (e < 103) {
  72162. return bits;
  72163. }
  72164. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72165. if (e > 142) {
  72166. bits |= 0x7c00;
  72167. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72168. * not Inf, so make sure we set one mantissa bit too. */
  72169. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72170. return bits;
  72171. }
  72172. /* If exponent underflows but not too much, return a denormal */
  72173. if (e < 113) {
  72174. m |= 0x0800;
  72175. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72176. * to 1, which is OK. */
  72177. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72178. return bits;
  72179. }
  72180. bits |= ((e - 112) << 10) | (m >> 1);
  72181. bits += m & 1;
  72182. return bits;
  72183. };
  72184. DDSTools._FromHalfFloat = function (value) {
  72185. var s = (value & 0x8000) >> 15;
  72186. var e = (value & 0x7C00) >> 10;
  72187. var f = value & 0x03FF;
  72188. if (e === 0) {
  72189. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72190. }
  72191. else if (e == 0x1F) {
  72192. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72193. }
  72194. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72195. };
  72196. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72197. var destArray = new Float32Array(dataLength);
  72198. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72199. var index = 0;
  72200. for (var y = 0; y < height; y++) {
  72201. for (var x = 0; x < width; x++) {
  72202. var srcPos = (x + y * width) * 4;
  72203. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72204. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72205. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72206. if (DDSTools.StoreLODInAlphaChannel) {
  72207. destArray[index + 3] = lod;
  72208. }
  72209. else {
  72210. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72211. }
  72212. index += 4;
  72213. }
  72214. }
  72215. return destArray;
  72216. };
  72217. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72218. if (DDSTools.StoreLODInAlphaChannel) {
  72219. var destArray = new Uint16Array(dataLength);
  72220. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72221. var index = 0;
  72222. for (var y = 0; y < height; y++) {
  72223. for (var x = 0; x < width; x++) {
  72224. var srcPos = (x + y * width) * 4;
  72225. destArray[index] = srcData[srcPos];
  72226. destArray[index + 1] = srcData[srcPos + 1];
  72227. destArray[index + 2] = srcData[srcPos + 2];
  72228. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72229. index += 4;
  72230. }
  72231. }
  72232. return destArray;
  72233. }
  72234. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  72235. };
  72236. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72237. if (DDSTools.StoreLODInAlphaChannel) {
  72238. var destArray = new Float32Array(dataLength);
  72239. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72240. var index = 0;
  72241. for (var y = 0; y < height; y++) {
  72242. for (var x = 0; x < width; x++) {
  72243. var srcPos = (x + y * width) * 4;
  72244. destArray[index] = srcData[srcPos];
  72245. destArray[index + 1] = srcData[srcPos + 1];
  72246. destArray[index + 2] = srcData[srcPos + 2];
  72247. destArray[index + 3] = lod;
  72248. index += 4;
  72249. }
  72250. }
  72251. return destArray;
  72252. }
  72253. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  72254. };
  72255. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72256. var destArray = new Uint8Array(dataLength);
  72257. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72258. var index = 0;
  72259. for (var y = 0; y < height; y++) {
  72260. for (var x = 0; x < width; x++) {
  72261. var srcPos = (x + y * width) * 4;
  72262. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  72263. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  72264. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  72265. if (DDSTools.StoreLODInAlphaChannel) {
  72266. destArray[index + 3] = lod;
  72267. }
  72268. else {
  72269. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  72270. }
  72271. index += 4;
  72272. }
  72273. }
  72274. return destArray;
  72275. };
  72276. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72277. var destArray = new Uint8Array(dataLength);
  72278. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72279. var index = 0;
  72280. for (var y = 0; y < height; y++) {
  72281. for (var x = 0; x < width; x++) {
  72282. var srcPos = (x + y * width) * 4;
  72283. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  72284. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  72285. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  72286. if (DDSTools.StoreLODInAlphaChannel) {
  72287. destArray[index + 3] = lod;
  72288. }
  72289. else {
  72290. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  72291. }
  72292. index += 4;
  72293. }
  72294. }
  72295. return destArray;
  72296. };
  72297. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  72298. var byteArray = new Uint8Array(dataLength);
  72299. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72300. var index = 0;
  72301. for (var y = 0; y < height; y++) {
  72302. for (var x = 0; x < width; x++) {
  72303. var srcPos = (x + y * width) * 4;
  72304. byteArray[index] = srcData[srcPos + rOffset];
  72305. byteArray[index + 1] = srcData[srcPos + gOffset];
  72306. byteArray[index + 2] = srcData[srcPos + bOffset];
  72307. byteArray[index + 3] = srcData[srcPos + aOffset];
  72308. index += 4;
  72309. }
  72310. }
  72311. return byteArray;
  72312. };
  72313. DDSTools._ExtractLongWordOrder = function (value) {
  72314. if (value === 0 || value === 255 || value === -16777216) {
  72315. return 0;
  72316. }
  72317. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  72318. };
  72319. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  72320. var byteArray = new Uint8Array(dataLength);
  72321. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72322. var index = 0;
  72323. for (var y = 0; y < height; y++) {
  72324. for (var x = 0; x < width; x++) {
  72325. var srcPos = (x + y * width) * 3;
  72326. byteArray[index] = srcData[srcPos + rOffset];
  72327. byteArray[index + 1] = srcData[srcPos + gOffset];
  72328. byteArray[index + 2] = srcData[srcPos + bOffset];
  72329. index += 3;
  72330. }
  72331. }
  72332. return byteArray;
  72333. };
  72334. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  72335. var byteArray = new Uint8Array(dataLength);
  72336. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72337. var index = 0;
  72338. for (var y = 0; y < height; y++) {
  72339. for (var x = 0; x < width; x++) {
  72340. var srcPos = (x + y * width);
  72341. byteArray[index] = srcData[srcPos];
  72342. index++;
  72343. }
  72344. }
  72345. return byteArray;
  72346. };
  72347. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  72348. if (lodIndex === void 0) { lodIndex = -1; }
  72349. var ext = engine.getCaps().s3tc;
  72350. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72351. var fourCC, width, height, dataLength = 0, dataOffset;
  72352. var byteArray, mipmapCount, mip;
  72353. var internalFormat = 0;
  72354. var format = 0;
  72355. var blockBytes = 1;
  72356. if (header[off_magic] !== DDS_MAGIC) {
  72357. BABYLON.Tools.Error("Invalid magic number in DDS header");
  72358. return;
  72359. }
  72360. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  72361. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  72362. return;
  72363. }
  72364. if (info.isCompressed && !ext) {
  72365. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  72366. return;
  72367. }
  72368. var bpp = header[off_RGBbpp];
  72369. dataOffset = header[off_size] + 4;
  72370. var computeFormats = false;
  72371. if (info.isFourCC) {
  72372. fourCC = header[off_pfFourCC];
  72373. switch (fourCC) {
  72374. case FOURCC_DXT1:
  72375. blockBytes = 8;
  72376. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  72377. break;
  72378. case FOURCC_DXT3:
  72379. blockBytes = 16;
  72380. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  72381. break;
  72382. case FOURCC_DXT5:
  72383. blockBytes = 16;
  72384. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  72385. break;
  72386. case FOURCC_D3DFMT_R16G16B16A16F:
  72387. computeFormats = true;
  72388. break;
  72389. case FOURCC_D3DFMT_R32G32B32A32F:
  72390. computeFormats = true;
  72391. break;
  72392. case FOURCC_DX10:
  72393. // There is an additionnal header so dataOffset need to be changed
  72394. dataOffset += 5 * 4; // 5 uints
  72395. var supported = false;
  72396. switch (info.dxgiFormat) {
  72397. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  72398. computeFormats = true;
  72399. supported = true;
  72400. break;
  72401. case DXGI_FORMAT_B8G8R8X8_UNORM:
  72402. info.isRGB = true;
  72403. info.isFourCC = false;
  72404. bpp = 32;
  72405. supported = true;
  72406. break;
  72407. }
  72408. if (supported) {
  72409. break;
  72410. }
  72411. default:
  72412. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  72413. return;
  72414. }
  72415. }
  72416. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  72417. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  72418. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  72419. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  72420. if (computeFormats) {
  72421. format = engine._getWebGLTextureType(info.textureType);
  72422. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72423. }
  72424. mipmapCount = 1;
  72425. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  72426. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72427. }
  72428. for (var face = 0; face < faces; face++) {
  72429. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  72430. width = header[off_width];
  72431. height = header[off_height];
  72432. for (mip = 0; mip < mipmapCount; ++mip) {
  72433. if (lodIndex === -1 || lodIndex === mip) {
  72434. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  72435. var i = (lodIndex === -1) ? mip : 0;
  72436. if (!info.isCompressed && info.isFourCC) {
  72437. dataLength = width * height * 4;
  72438. var floatArray = null;
  72439. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  72440. if (bpp === 128) {
  72441. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72442. }
  72443. else if (bpp === 64) {
  72444. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72445. }
  72446. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72447. format = engine._getWebGLTextureType(info.textureType);
  72448. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72449. }
  72450. else {
  72451. if (bpp === 128) {
  72452. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72453. }
  72454. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  72455. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72456. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72457. format = engine._getWebGLTextureType(info.textureType);
  72458. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72459. }
  72460. else {
  72461. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72462. }
  72463. }
  72464. if (floatArray) {
  72465. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  72466. }
  72467. }
  72468. else if (info.isRGB) {
  72469. if (bpp === 24) {
  72470. dataLength = width * height * 3;
  72471. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  72472. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  72473. }
  72474. else {
  72475. dataLength = width * height * 4;
  72476. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  72477. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  72478. }
  72479. }
  72480. else if (info.isLuminance) {
  72481. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  72482. var unpaddedRowSize = width;
  72483. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  72484. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  72485. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  72486. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  72487. }
  72488. else {
  72489. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  72490. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  72491. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  72492. }
  72493. }
  72494. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  72495. width *= 0.5;
  72496. height *= 0.5;
  72497. width = Math.max(1.0, width);
  72498. height = Math.max(1.0, height);
  72499. }
  72500. if (currentFace !== undefined) {
  72501. // Loading a single face
  72502. break;
  72503. }
  72504. }
  72505. };
  72506. DDSTools.StoreLODInAlphaChannel = false;
  72507. return DDSTools;
  72508. }());
  72509. BABYLON.DDSTools = DDSTools;
  72510. })(BABYLON || (BABYLON = {}));
  72511. //# sourceMappingURL=babylon.dds.js.map
  72512. var BABYLON;
  72513. (function (BABYLON) {
  72514. /**
  72515. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  72516. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  72517. */
  72518. var KhronosTextureContainer = /** @class */ (function () {
  72519. /**
  72520. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  72521. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  72522. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  72523. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  72524. */
  72525. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  72526. this.arrayBuffer = arrayBuffer;
  72527. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  72528. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  72529. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  72530. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  72531. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  72532. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  72533. BABYLON.Tools.Error("texture missing KTX identifier");
  72534. return;
  72535. }
  72536. // load the reset of the header in native 32 bit int
  72537. var header = new Int32Array(this.arrayBuffer, 12, 13);
  72538. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  72539. var oppositeEndianess = header[0] === 0x01020304;
  72540. // read all the header elements in order they exist in the file, without modification (sans endainness)
  72541. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  72542. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  72543. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  72544. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  72545. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  72546. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  72547. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  72548. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  72549. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  72550. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  72551. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  72552. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  72553. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  72554. if (this.glType !== 0) {
  72555. BABYLON.Tools.Error("only compressed formats currently supported");
  72556. return;
  72557. }
  72558. else {
  72559. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  72560. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  72561. }
  72562. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  72563. BABYLON.Tools.Error("only 2D textures currently supported");
  72564. return;
  72565. }
  72566. if (this.numberOfArrayElements !== 0) {
  72567. BABYLON.Tools.Error("texture arrays not currently supported");
  72568. return;
  72569. }
  72570. if (this.numberOfFaces !== facesExpected) {
  72571. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  72572. return;
  72573. }
  72574. // we now have a completely validated file, so could use existence of loadType as success
  72575. // would need to make this more elaborate & adjust checks above to support more than one load type
  72576. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  72577. }
  72578. // not as fast hardware based, but will probably never need to use
  72579. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  72580. return ((val & 0xFF) << 24)
  72581. | ((val & 0xFF00) << 8)
  72582. | ((val >> 8) & 0xFF00)
  72583. | ((val >> 24) & 0xFF);
  72584. };
  72585. /**
  72586. * It is assumed that the texture has already been created & is currently bound
  72587. */
  72588. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  72589. switch (this.loadType) {
  72590. case KhronosTextureContainer.COMPRESSED_2D:
  72591. this._upload2DCompressedLevels(gl, loadMipmaps);
  72592. break;
  72593. case KhronosTextureContainer.TEX_2D:
  72594. case KhronosTextureContainer.COMPRESSED_3D:
  72595. case KhronosTextureContainer.TEX_3D:
  72596. }
  72597. };
  72598. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  72599. // initialize width & height for level 1
  72600. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  72601. var width = this.pixelWidth;
  72602. var height = this.pixelHeight;
  72603. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  72604. for (var level = 0; level < mipmapCount; level++) {
  72605. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  72606. for (var face = 0; face < this.numberOfFaces; face++) {
  72607. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  72608. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  72609. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  72610. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  72611. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  72612. }
  72613. width = Math.max(1.0, width * 0.5);
  72614. height = Math.max(1.0, height * 0.5);
  72615. }
  72616. };
  72617. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  72618. // load types
  72619. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  72620. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  72621. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  72622. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  72623. return KhronosTextureContainer;
  72624. }());
  72625. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  72626. })(BABYLON || (BABYLON = {}));
  72627. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  72628. var BABYLON;
  72629. (function (BABYLON) {
  72630. var Debug = /** @class */ (function () {
  72631. function Debug() {
  72632. }
  72633. Debug.AxesViewer = /** @class */ (function () {
  72634. function AxesViewer(scene, scaleLines) {
  72635. if (scaleLines === void 0) { scaleLines = 1; }
  72636. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72637. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72638. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72639. this.scaleLines = 1;
  72640. this.scaleLines = scaleLines;
  72641. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  72642. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  72643. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  72644. this._xmesh.renderingGroupId = 2;
  72645. this._ymesh.renderingGroupId = 2;
  72646. this._zmesh.renderingGroupId = 2;
  72647. this._xmesh.material.checkReadyOnlyOnce = true;
  72648. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  72649. this._ymesh.material.checkReadyOnlyOnce = true;
  72650. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  72651. this._zmesh.material.checkReadyOnlyOnce = true;
  72652. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  72653. this.scene = scene;
  72654. }
  72655. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  72656. var scaleLines = this.scaleLines;
  72657. if (this._xmesh) {
  72658. this._xmesh.position.copyFrom(position);
  72659. }
  72660. if (this._ymesh) {
  72661. this._ymesh.position.copyFrom(position);
  72662. }
  72663. if (this._zmesh) {
  72664. this._zmesh.position.copyFrom(position);
  72665. }
  72666. var point2 = this._xline[1];
  72667. point2.x = xaxis.x * scaleLines;
  72668. point2.y = xaxis.y * scaleLines;
  72669. point2.z = xaxis.z * scaleLines;
  72670. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  72671. point2 = this._yline[1];
  72672. point2.x = yaxis.x * scaleLines;
  72673. point2.y = yaxis.y * scaleLines;
  72674. point2.z = yaxis.z * scaleLines;
  72675. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  72676. point2 = this._zline[1];
  72677. point2.x = zaxis.x * scaleLines;
  72678. point2.y = zaxis.y * scaleLines;
  72679. point2.z = zaxis.z * scaleLines;
  72680. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  72681. };
  72682. AxesViewer.prototype.dispose = function () {
  72683. if (this._xmesh) {
  72684. this._xmesh.dispose();
  72685. }
  72686. if (this._ymesh) {
  72687. this._ymesh.dispose();
  72688. }
  72689. if (this._zmesh) {
  72690. this._zmesh.dispose();
  72691. }
  72692. this._xmesh = null;
  72693. this._ymesh = null;
  72694. this._zmesh = null;
  72695. this.scene = null;
  72696. };
  72697. return AxesViewer;
  72698. }());
  72699. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  72700. __extends(BoneAxesViewer, _super);
  72701. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  72702. if (scaleLines === void 0) { scaleLines = 1; }
  72703. var _this = _super.call(this, scene, scaleLines) || this;
  72704. _this.pos = BABYLON.Vector3.Zero();
  72705. _this.xaxis = BABYLON.Vector3.Zero();
  72706. _this.yaxis = BABYLON.Vector3.Zero();
  72707. _this.zaxis = BABYLON.Vector3.Zero();
  72708. _this.mesh = mesh;
  72709. _this.bone = bone;
  72710. return _this;
  72711. }
  72712. BoneAxesViewer.prototype.update = function () {
  72713. if (!this.mesh || !this.bone) {
  72714. return;
  72715. }
  72716. var bone = this.bone;
  72717. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  72718. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  72719. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  72720. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  72721. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  72722. };
  72723. BoneAxesViewer.prototype.dispose = function () {
  72724. if (this.mesh) {
  72725. this.mesh = null;
  72726. this.bone = null;
  72727. _super.prototype.dispose.call(this);
  72728. }
  72729. };
  72730. return BoneAxesViewer;
  72731. }(Debug.AxesViewer));
  72732. Debug.PhysicsViewer = /** @class */ (function () {
  72733. function PhysicsViewer(scene) {
  72734. this._impostors = [];
  72735. this._meshes = [];
  72736. this._numMeshes = 0;
  72737. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72738. var physicEngine = this._scene.getPhysicsEngine();
  72739. if (physicEngine) {
  72740. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  72741. }
  72742. }
  72743. PhysicsViewer.prototype._updateDebugMeshes = function () {
  72744. var plugin = this._physicsEnginePlugin;
  72745. for (var i = 0; i < this._numMeshes; i++) {
  72746. var impostor = this._impostors[i];
  72747. if (!impostor) {
  72748. continue;
  72749. }
  72750. if (impostor.isDisposed) {
  72751. this.hideImpostor(this._impostors[i--]);
  72752. }
  72753. else {
  72754. var mesh = this._meshes[i];
  72755. if (mesh && plugin) {
  72756. plugin.syncMeshWithImpostor(mesh, impostor);
  72757. }
  72758. }
  72759. }
  72760. };
  72761. PhysicsViewer.prototype.showImpostor = function (impostor) {
  72762. if (!this._scene) {
  72763. return;
  72764. }
  72765. for (var i = 0; i < this._numMeshes; i++) {
  72766. if (this._impostors[i] == impostor) {
  72767. return;
  72768. }
  72769. }
  72770. var debugMesh = this._getDebugMesh(impostor, this._scene);
  72771. if (debugMesh) {
  72772. this._impostors[this._numMeshes] = impostor;
  72773. this._meshes[this._numMeshes] = debugMesh;
  72774. if (this._numMeshes === 0) {
  72775. this._renderFunction = this._updateDebugMeshes.bind(this);
  72776. this._scene.registerBeforeRender(this._renderFunction);
  72777. }
  72778. this._numMeshes++;
  72779. }
  72780. };
  72781. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  72782. if (!impostor || !this._scene) {
  72783. return;
  72784. }
  72785. var removed = false;
  72786. for (var i = 0; i < this._numMeshes; i++) {
  72787. if (this._impostors[i] == impostor) {
  72788. var mesh = this._meshes[i];
  72789. if (!mesh) {
  72790. continue;
  72791. }
  72792. this._scene.removeMesh(mesh);
  72793. mesh.dispose();
  72794. this._numMeshes--;
  72795. if (this._numMeshes > 0) {
  72796. this._meshes[i] = this._meshes[this._numMeshes];
  72797. this._impostors[i] = this._impostors[this._numMeshes];
  72798. this._meshes[this._numMeshes] = null;
  72799. this._impostors[this._numMeshes] = null;
  72800. }
  72801. else {
  72802. this._meshes[0] = null;
  72803. this._impostors[0] = null;
  72804. }
  72805. removed = true;
  72806. break;
  72807. }
  72808. }
  72809. if (removed && this._numMeshes === 0) {
  72810. this._scene.unregisterBeforeRender(this._renderFunction);
  72811. }
  72812. };
  72813. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  72814. if (!this._debugMaterial) {
  72815. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  72816. this._debugMaterial.wireframe = true;
  72817. }
  72818. return this._debugMaterial;
  72819. };
  72820. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  72821. if (!this._debugBoxMesh) {
  72822. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  72823. this._debugBoxMesh.renderingGroupId = 1;
  72824. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  72825. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  72826. scene.removeMesh(this._debugBoxMesh);
  72827. }
  72828. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  72829. };
  72830. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  72831. if (!this._debugSphereMesh) {
  72832. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  72833. this._debugSphereMesh.renderingGroupId = 1;
  72834. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  72835. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  72836. scene.removeMesh(this._debugSphereMesh);
  72837. }
  72838. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  72839. };
  72840. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  72841. var mesh = null;
  72842. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  72843. mesh = this._getDebugBoxMesh(scene);
  72844. impostor.getBoxSizeToRef(mesh.scaling);
  72845. }
  72846. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  72847. mesh = this._getDebugSphereMesh(scene);
  72848. var radius = impostor.getRadius();
  72849. mesh.scaling.x = radius * 2;
  72850. mesh.scaling.y = radius * 2;
  72851. mesh.scaling.z = radius * 2;
  72852. }
  72853. return mesh;
  72854. };
  72855. PhysicsViewer.prototype.dispose = function () {
  72856. for (var i = 0; i < this._numMeshes; i++) {
  72857. this.hideImpostor(this._impostors[i]);
  72858. }
  72859. if (this._debugBoxMesh) {
  72860. this._debugBoxMesh.dispose();
  72861. }
  72862. if (this._debugSphereMesh) {
  72863. this._debugSphereMesh.dispose();
  72864. }
  72865. if (this._debugMaterial) {
  72866. this._debugMaterial.dispose();
  72867. }
  72868. this._impostors.length = 0;
  72869. this._scene = null;
  72870. this._physicsEnginePlugin = null;
  72871. };
  72872. return PhysicsViewer;
  72873. }());
  72874. Debug.SkeletonViewer = /** @class */ (function () {
  72875. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  72876. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  72877. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  72878. this.skeleton = skeleton;
  72879. this.mesh = mesh;
  72880. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  72881. this.renderingGroupId = renderingGroupId;
  72882. this.color = BABYLON.Color3.White();
  72883. this._debugLines = new Array();
  72884. this._isEnabled = false;
  72885. this._scene = scene;
  72886. this.update();
  72887. this._renderFunction = this.update.bind(this);
  72888. }
  72889. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  72890. get: function () {
  72891. return this._isEnabled;
  72892. },
  72893. set: function (value) {
  72894. if (this._isEnabled === value) {
  72895. return;
  72896. }
  72897. this._isEnabled = value;
  72898. if (value) {
  72899. this._scene.registerBeforeRender(this._renderFunction);
  72900. }
  72901. else {
  72902. this._scene.unregisterBeforeRender(this._renderFunction);
  72903. }
  72904. },
  72905. enumerable: true,
  72906. configurable: true
  72907. });
  72908. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  72909. if (x === void 0) { x = 0; }
  72910. if (y === void 0) { y = 0; }
  72911. if (z === void 0) { z = 0; }
  72912. var tmat = BABYLON.Tmp.Matrix[0];
  72913. var parentBone = bone.getParent();
  72914. tmat.copyFrom(bone.getLocalMatrix());
  72915. if (x !== 0 || y !== 0 || z !== 0) {
  72916. var tmat2 = BABYLON.Tmp.Matrix[1];
  72917. BABYLON.Matrix.IdentityToRef(tmat2);
  72918. tmat2.m[12] = x;
  72919. tmat2.m[13] = y;
  72920. tmat2.m[14] = z;
  72921. tmat2.multiplyToRef(tmat, tmat);
  72922. }
  72923. if (parentBone) {
  72924. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  72925. }
  72926. tmat.multiplyToRef(meshMat, tmat);
  72927. position.x = tmat.m[12];
  72928. position.y = tmat.m[13];
  72929. position.z = tmat.m[14];
  72930. };
  72931. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  72932. var len = bones.length;
  72933. var meshPos = this.mesh.position;
  72934. for (var i = 0; i < len; i++) {
  72935. var bone = bones[i];
  72936. var points = this._debugLines[i];
  72937. if (!points) {
  72938. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72939. this._debugLines[i] = points;
  72940. }
  72941. this._getBonePosition(points[0], bone, meshMat);
  72942. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  72943. points[0].subtractInPlace(meshPos);
  72944. points[1].subtractInPlace(meshPos);
  72945. }
  72946. };
  72947. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  72948. var len = bones.length;
  72949. var boneNum = 0;
  72950. var meshPos = this.mesh.position;
  72951. for (var i = len - 1; i >= 0; i--) {
  72952. var childBone = bones[i];
  72953. var parentBone = childBone.getParent();
  72954. if (!parentBone) {
  72955. continue;
  72956. }
  72957. var points = this._debugLines[boneNum];
  72958. if (!points) {
  72959. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  72960. this._debugLines[boneNum] = points;
  72961. }
  72962. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  72963. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  72964. points[0].subtractInPlace(meshPos);
  72965. points[1].subtractInPlace(meshPos);
  72966. boneNum++;
  72967. }
  72968. };
  72969. SkeletonViewer.prototype.update = function () {
  72970. if (this.autoUpdateBonesMatrices) {
  72971. this.skeleton.computeAbsoluteTransforms();
  72972. }
  72973. if (this.skeleton.bones[0].length === undefined) {
  72974. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  72975. }
  72976. else {
  72977. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  72978. }
  72979. if (!this._debugMesh) {
  72980. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  72981. this._debugMesh.renderingGroupId = this.renderingGroupId;
  72982. }
  72983. else {
  72984. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  72985. }
  72986. this._debugMesh.position.copyFrom(this.mesh.position);
  72987. this._debugMesh.color = this.color;
  72988. };
  72989. SkeletonViewer.prototype.dispose = function () {
  72990. if (this._debugMesh) {
  72991. this.isEnabled = false;
  72992. this._debugMesh.dispose();
  72993. this._debugMesh = null;
  72994. }
  72995. };
  72996. return SkeletonViewer;
  72997. }());
  72998. return Debug;
  72999. }());
  73000. BABYLON.Debug = Debug;
  73001. })(BABYLON || (BABYLON = {}));
  73002. //# sourceMappingURL=babylon.debugModules.js.map
  73003. var BABYLON;
  73004. (function (BABYLON) {
  73005. var RayHelper = /** @class */ (function () {
  73006. function RayHelper(ray) {
  73007. this.ray = ray;
  73008. }
  73009. RayHelper.CreateAndShow = function (ray, scene, color) {
  73010. var helper = new RayHelper(ray);
  73011. helper.show(scene, color);
  73012. return helper;
  73013. };
  73014. RayHelper.prototype.show = function (scene, color) {
  73015. if (!this._renderFunction && this.ray) {
  73016. var ray = this.ray;
  73017. this._renderFunction = this._render.bind(this);
  73018. this._scene = scene;
  73019. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73020. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73021. if (this._renderFunction) {
  73022. this._scene.registerBeforeRender(this._renderFunction);
  73023. }
  73024. }
  73025. if (color && this._renderLine) {
  73026. this._renderLine.color.copyFrom(color);
  73027. }
  73028. };
  73029. RayHelper.prototype.hide = function () {
  73030. if (this._renderFunction && this._scene) {
  73031. this._scene.unregisterBeforeRender(this._renderFunction);
  73032. this._scene = null;
  73033. this._renderFunction = null;
  73034. if (this._renderLine) {
  73035. this._renderLine.dispose();
  73036. this._renderLine = null;
  73037. }
  73038. this._renderPoints = [];
  73039. }
  73040. };
  73041. RayHelper.prototype._render = function () {
  73042. var ray = this.ray;
  73043. if (!ray) {
  73044. return;
  73045. }
  73046. var point = this._renderPoints[1];
  73047. var len = Math.min(ray.length, 1000000);
  73048. point.copyFrom(ray.direction);
  73049. point.scaleInPlace(len);
  73050. point.addInPlace(ray.origin);
  73051. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73052. };
  73053. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73054. this._attachedToMesh = mesh;
  73055. var ray = this.ray;
  73056. if (!ray) {
  73057. return;
  73058. }
  73059. if (!ray.direction) {
  73060. ray.direction = BABYLON.Vector3.Zero();
  73061. }
  73062. if (!ray.origin) {
  73063. ray.origin = BABYLON.Vector3.Zero();
  73064. }
  73065. if (length) {
  73066. ray.length = length;
  73067. }
  73068. if (!meshSpaceOrigin) {
  73069. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73070. }
  73071. if (!meshSpaceDirection) {
  73072. // -1 so that this will work with Mesh.lookAt
  73073. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73074. }
  73075. if (!this._meshSpaceDirection) {
  73076. this._meshSpaceDirection = meshSpaceDirection.clone();
  73077. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73078. }
  73079. else {
  73080. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73081. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73082. }
  73083. if (!this._updateToMeshFunction) {
  73084. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73085. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73086. }
  73087. this._updateToMesh();
  73088. };
  73089. RayHelper.prototype.detachFromMesh = function () {
  73090. if (this._attachedToMesh) {
  73091. if (this._updateToMeshFunction) {
  73092. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73093. }
  73094. this._attachedToMesh = null;
  73095. this._updateToMeshFunction = null;
  73096. }
  73097. };
  73098. RayHelper.prototype._updateToMesh = function () {
  73099. var ray = this.ray;
  73100. if (!this._attachedToMesh || !ray) {
  73101. return;
  73102. }
  73103. if (this._attachedToMesh._isDisposed) {
  73104. this.detachFromMesh();
  73105. return;
  73106. }
  73107. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73108. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73109. };
  73110. RayHelper.prototype.dispose = function () {
  73111. this.hide();
  73112. this.detachFromMesh();
  73113. this.ray = null;
  73114. };
  73115. return RayHelper;
  73116. }());
  73117. BABYLON.RayHelper = RayHelper;
  73118. })(BABYLON || (BABYLON = {}));
  73119. //# sourceMappingURL=babylon.rayHelper.js.map
  73120. var BABYLON;
  73121. (function (BABYLON) {
  73122. // load the inspector using require, if not present in the global namespace.
  73123. var DebugLayer = /** @class */ (function () {
  73124. function DebugLayer(scene) {
  73125. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73126. this._scene = scene;
  73127. // load inspector using require, if it doesn't exist on the global namespace.
  73128. }
  73129. /** Creates the inspector window. */
  73130. DebugLayer.prototype._createInspector = function (config) {
  73131. if (config === void 0) { config = {}; }
  73132. var popup = config.popup || false;
  73133. var initialTab = config.initialTab || 0;
  73134. var parentElement = config.parentElement || null;
  73135. if (!this._inspector) {
  73136. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73137. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73138. } // else nothing to do,; instance is already existing
  73139. };
  73140. DebugLayer.prototype.isVisible = function () {
  73141. if (!this._inspector) {
  73142. return false;
  73143. }
  73144. return true;
  73145. };
  73146. DebugLayer.prototype.hide = function () {
  73147. if (this._inspector) {
  73148. try {
  73149. this._inspector.dispose();
  73150. }
  73151. catch (e) {
  73152. // If the inspector has been removed directly from the inspector tool
  73153. }
  73154. this._inspector = null;
  73155. }
  73156. };
  73157. DebugLayer.prototype.show = function (config) {
  73158. if (config === void 0) { config = {}; }
  73159. if (typeof this.BJSINSPECTOR == 'undefined') {
  73160. // Load inspector and add it to the DOM
  73161. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73162. }
  73163. else {
  73164. // Otherwise creates the inspector
  73165. this._createInspector(config);
  73166. }
  73167. };
  73168. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73169. return DebugLayer;
  73170. }());
  73171. BABYLON.DebugLayer = DebugLayer;
  73172. })(BABYLON || (BABYLON = {}));
  73173. //# sourceMappingURL=babylon.debugLayer.js.map
  73174. var BABYLON;
  73175. (function (BABYLON) {
  73176. var BoundingBoxRenderer = /** @class */ (function () {
  73177. function BoundingBoxRenderer(scene) {
  73178. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73179. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73180. this.showBackLines = true;
  73181. this.renderList = new BABYLON.SmartArray(32);
  73182. this._vertexBuffers = {};
  73183. this._scene = scene;
  73184. }
  73185. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73186. if (this._colorShader) {
  73187. return;
  73188. }
  73189. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73190. attributes: [BABYLON.VertexBuffer.PositionKind],
  73191. uniforms: ["world", "viewProjection", "color"]
  73192. });
  73193. var engine = this._scene.getEngine();
  73194. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73195. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73196. this._createIndexBuffer();
  73197. };
  73198. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73199. var engine = this._scene.getEngine();
  73200. 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]);
  73201. };
  73202. BoundingBoxRenderer.prototype._rebuild = function () {
  73203. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73204. if (vb) {
  73205. vb._rebuild();
  73206. }
  73207. this._createIndexBuffer();
  73208. };
  73209. BoundingBoxRenderer.prototype.reset = function () {
  73210. this.renderList.reset();
  73211. };
  73212. BoundingBoxRenderer.prototype.render = function () {
  73213. if (this.renderList.length === 0) {
  73214. return;
  73215. }
  73216. this._prepareRessources();
  73217. if (!this._colorShader.isReady()) {
  73218. return;
  73219. }
  73220. var engine = this._scene.getEngine();
  73221. engine.setDepthWrite(false);
  73222. this._colorShader._preBind();
  73223. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73224. var boundingBox = this.renderList.data[boundingBoxIndex];
  73225. var min = boundingBox.minimum;
  73226. var max = boundingBox.maximum;
  73227. var diff = max.subtract(min);
  73228. var median = min.add(diff.scale(0.5));
  73229. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73230. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73231. .multiply(boundingBox.getWorldMatrix());
  73232. // VBOs
  73233. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73234. if (this.showBackLines) {
  73235. // Back
  73236. engine.setDepthFunctionToGreaterOrEqual();
  73237. this._scene.resetCachedMaterial();
  73238. this._colorShader.setColor4("color", this.backColor.toColor4());
  73239. this._colorShader.bind(worldMatrix);
  73240. // Draw order
  73241. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73242. }
  73243. // Front
  73244. engine.setDepthFunctionToLess();
  73245. this._scene.resetCachedMaterial();
  73246. this._colorShader.setColor4("color", this.frontColor.toColor4());
  73247. this._colorShader.bind(worldMatrix);
  73248. // Draw order
  73249. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73250. }
  73251. this._colorShader.unbind();
  73252. engine.setDepthFunctionToLessOrEqual();
  73253. engine.setDepthWrite(true);
  73254. };
  73255. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  73256. this._prepareRessources();
  73257. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  73258. return;
  73259. }
  73260. var engine = this._scene.getEngine();
  73261. engine.setDepthWrite(false);
  73262. engine.setColorWrite(false);
  73263. this._colorShader._preBind();
  73264. var boundingBox = mesh._boundingInfo.boundingBox;
  73265. var min = boundingBox.minimum;
  73266. var max = boundingBox.maximum;
  73267. var diff = max.subtract(min);
  73268. var median = min.add(diff.scale(0.5));
  73269. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73270. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73271. .multiply(boundingBox.getWorldMatrix());
  73272. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73273. engine.setDepthFunctionToLess();
  73274. this._scene.resetCachedMaterial();
  73275. this._colorShader.bind(worldMatrix);
  73276. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73277. this._colorShader.unbind();
  73278. engine.setDepthFunctionToLessOrEqual();
  73279. engine.setDepthWrite(true);
  73280. engine.setColorWrite(true);
  73281. };
  73282. BoundingBoxRenderer.prototype.dispose = function () {
  73283. if (!this._colorShader) {
  73284. return;
  73285. }
  73286. this.renderList.dispose();
  73287. this._colorShader.dispose();
  73288. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73289. if (buffer) {
  73290. buffer.dispose();
  73291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73292. }
  73293. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73294. };
  73295. return BoundingBoxRenderer;
  73296. }());
  73297. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  73298. })(BABYLON || (BABYLON = {}));
  73299. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  73300. var BABYLON;
  73301. (function (BABYLON) {
  73302. var MorphTarget = /** @class */ (function () {
  73303. function MorphTarget(name, influence) {
  73304. if (influence === void 0) { influence = 0; }
  73305. this.name = name;
  73306. this.animations = new Array();
  73307. this._positions = null;
  73308. this._normals = null;
  73309. this._tangents = null;
  73310. this.onInfluenceChanged = new BABYLON.Observable();
  73311. this.influence = influence;
  73312. }
  73313. Object.defineProperty(MorphTarget.prototype, "influence", {
  73314. get: function () {
  73315. return this._influence;
  73316. },
  73317. set: function (influence) {
  73318. if (this._influence === influence) {
  73319. return;
  73320. }
  73321. var previous = this._influence;
  73322. this._influence = influence;
  73323. if (this.onInfluenceChanged.hasObservers) {
  73324. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  73325. }
  73326. },
  73327. enumerable: true,
  73328. configurable: true
  73329. });
  73330. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  73331. get: function () {
  73332. return !!this._positions;
  73333. },
  73334. enumerable: true,
  73335. configurable: true
  73336. });
  73337. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  73338. get: function () {
  73339. return !!this._normals;
  73340. },
  73341. enumerable: true,
  73342. configurable: true
  73343. });
  73344. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  73345. get: function () {
  73346. return !!this._tangents;
  73347. },
  73348. enumerable: true,
  73349. configurable: true
  73350. });
  73351. MorphTarget.prototype.setPositions = function (data) {
  73352. this._positions = data;
  73353. };
  73354. MorphTarget.prototype.getPositions = function () {
  73355. return this._positions;
  73356. };
  73357. MorphTarget.prototype.setNormals = function (data) {
  73358. this._normals = data;
  73359. };
  73360. MorphTarget.prototype.getNormals = function () {
  73361. return this._normals;
  73362. };
  73363. MorphTarget.prototype.setTangents = function (data) {
  73364. this._tangents = data;
  73365. };
  73366. MorphTarget.prototype.getTangents = function () {
  73367. return this._tangents;
  73368. };
  73369. /**
  73370. * Serializes the current target into a Serialization object.
  73371. * Returns the serialized object.
  73372. */
  73373. MorphTarget.prototype.serialize = function () {
  73374. var serializationObject = {};
  73375. serializationObject.name = this.name;
  73376. serializationObject.influence = this.influence;
  73377. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  73378. if (this.hasNormals) {
  73379. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  73380. }
  73381. if (this.hasTangents) {
  73382. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  73383. }
  73384. // Animations
  73385. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  73386. return serializationObject;
  73387. };
  73388. // Statics
  73389. MorphTarget.Parse = function (serializationObject) {
  73390. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  73391. result.setPositions(serializationObject.positions);
  73392. if (serializationObject.normals) {
  73393. result.setNormals(serializationObject.normals);
  73394. }
  73395. if (serializationObject.tangents) {
  73396. result.setTangents(serializationObject.tangents);
  73397. }
  73398. // Animations
  73399. if (serializationObject.animations) {
  73400. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  73401. var parsedAnimation = serializationObject.animations[animationIndex];
  73402. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73403. }
  73404. }
  73405. return result;
  73406. };
  73407. MorphTarget.FromMesh = function (mesh, name, influence) {
  73408. if (!name) {
  73409. name = mesh.name;
  73410. }
  73411. var result = new MorphTarget(name, influence);
  73412. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73413. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73414. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  73415. }
  73416. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  73417. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  73418. }
  73419. return result;
  73420. };
  73421. return MorphTarget;
  73422. }());
  73423. BABYLON.MorphTarget = MorphTarget;
  73424. })(BABYLON || (BABYLON = {}));
  73425. //# sourceMappingURL=babylon.morphTarget.js.map
  73426. var BABYLON;
  73427. (function (BABYLON) {
  73428. var MorphTargetManager = /** @class */ (function () {
  73429. function MorphTargetManager(scene) {
  73430. if (scene === void 0) { scene = null; }
  73431. this._targets = new Array();
  73432. this._targetObservable = new Array();
  73433. this._activeTargets = new BABYLON.SmartArray(16);
  73434. this._supportsNormals = false;
  73435. this._supportsTangents = false;
  73436. this._vertexCount = 0;
  73437. this._uniqueId = 0;
  73438. this._tempInfluences = new Array();
  73439. if (!scene) {
  73440. scene = BABYLON.Engine.LastCreatedScene;
  73441. }
  73442. this._scene = scene;
  73443. if (this._scene) {
  73444. this._scene.morphTargetManagers.push(this);
  73445. this._uniqueId = this._scene.getUniqueId();
  73446. }
  73447. }
  73448. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  73449. get: function () {
  73450. return this._uniqueId;
  73451. },
  73452. enumerable: true,
  73453. configurable: true
  73454. });
  73455. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  73456. get: function () {
  73457. return this._vertexCount;
  73458. },
  73459. enumerable: true,
  73460. configurable: true
  73461. });
  73462. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  73463. get: function () {
  73464. return this._supportsNormals;
  73465. },
  73466. enumerable: true,
  73467. configurable: true
  73468. });
  73469. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  73470. get: function () {
  73471. return this._supportsTangents;
  73472. },
  73473. enumerable: true,
  73474. configurable: true
  73475. });
  73476. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  73477. get: function () {
  73478. return this._targets.length;
  73479. },
  73480. enumerable: true,
  73481. configurable: true
  73482. });
  73483. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  73484. get: function () {
  73485. return this._activeTargets.length;
  73486. },
  73487. enumerable: true,
  73488. configurable: true
  73489. });
  73490. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  73491. get: function () {
  73492. return this._influences;
  73493. },
  73494. enumerable: true,
  73495. configurable: true
  73496. });
  73497. MorphTargetManager.prototype.getActiveTarget = function (index) {
  73498. return this._activeTargets.data[index];
  73499. };
  73500. MorphTargetManager.prototype.getTarget = function (index) {
  73501. return this._targets[index];
  73502. };
  73503. MorphTargetManager.prototype.addTarget = function (target) {
  73504. var _this = this;
  73505. this._targets.push(target);
  73506. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  73507. _this._syncActiveTargets(needUpdate);
  73508. }));
  73509. this._syncActiveTargets(true);
  73510. };
  73511. MorphTargetManager.prototype.removeTarget = function (target) {
  73512. var index = this._targets.indexOf(target);
  73513. if (index >= 0) {
  73514. this._targets.splice(index, 1);
  73515. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  73516. this._syncActiveTargets(true);
  73517. }
  73518. };
  73519. /**
  73520. * Serializes the current manager into a Serialization object.
  73521. * Returns the serialized object.
  73522. */
  73523. MorphTargetManager.prototype.serialize = function () {
  73524. var serializationObject = {};
  73525. serializationObject.id = this.uniqueId;
  73526. serializationObject.targets = [];
  73527. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73528. var target = _a[_i];
  73529. serializationObject.targets.push(target.serialize());
  73530. }
  73531. return serializationObject;
  73532. };
  73533. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  73534. var influenceCount = 0;
  73535. this._activeTargets.reset();
  73536. this._supportsNormals = true;
  73537. this._supportsTangents = true;
  73538. this._vertexCount = 0;
  73539. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73540. var target = _a[_i];
  73541. this._activeTargets.push(target);
  73542. this._tempInfluences[influenceCount++] = target.influence;
  73543. var positions = target.getPositions();
  73544. if (positions) {
  73545. this._supportsNormals = this._supportsNormals && target.hasNormals;
  73546. this._supportsTangents = this._supportsTangents && target.hasTangents;
  73547. var vertexCount = positions.length / 3;
  73548. if (this._vertexCount === 0) {
  73549. this._vertexCount = vertexCount;
  73550. }
  73551. else if (this._vertexCount !== vertexCount) {
  73552. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  73553. return;
  73554. }
  73555. }
  73556. }
  73557. if (!this._influences || this._influences.length !== influenceCount) {
  73558. this._influences = new Float32Array(influenceCount);
  73559. }
  73560. for (var index = 0; index < influenceCount; index++) {
  73561. this._influences[index] = this._tempInfluences[index];
  73562. }
  73563. if (needUpdate && this._scene) {
  73564. // Flag meshes as dirty to resync with the active targets
  73565. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  73566. var mesh = _c[_b];
  73567. if (mesh.morphTargetManager === this) {
  73568. mesh._syncGeometryWithMorphTargetManager();
  73569. }
  73570. }
  73571. }
  73572. };
  73573. // Statics
  73574. MorphTargetManager.Parse = function (serializationObject, scene) {
  73575. var result = new MorphTargetManager(scene);
  73576. result._uniqueId = serializationObject.id;
  73577. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  73578. var targetData = _a[_i];
  73579. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  73580. }
  73581. return result;
  73582. };
  73583. return MorphTargetManager;
  73584. }());
  73585. BABYLON.MorphTargetManager = MorphTargetManager;
  73586. })(BABYLON || (BABYLON = {}));
  73587. //# sourceMappingURL=babylon.morphTargetManager.js.map
  73588. var BABYLON;
  73589. (function (BABYLON) {
  73590. var Octree = /** @class */ (function () {
  73591. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  73592. if (maxDepth === void 0) { maxDepth = 2; }
  73593. this.maxDepth = maxDepth;
  73594. this.dynamicContent = new Array();
  73595. this._maxBlockCapacity = maxBlockCapacity || 64;
  73596. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  73597. this._creationFunc = creationFunc;
  73598. }
  73599. // Methods
  73600. Octree.prototype.update = function (worldMin, worldMax, entries) {
  73601. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  73602. };
  73603. Octree.prototype.addMesh = function (entry) {
  73604. for (var index = 0; index < this.blocks.length; index++) {
  73605. var block = this.blocks[index];
  73606. block.addEntry(entry);
  73607. }
  73608. };
  73609. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  73610. this._selectionContent.reset();
  73611. for (var index = 0; index < this.blocks.length; index++) {
  73612. var block = this.blocks[index];
  73613. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  73614. }
  73615. if (allowDuplicate) {
  73616. this._selectionContent.concat(this.dynamicContent);
  73617. }
  73618. else {
  73619. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73620. }
  73621. return this._selectionContent;
  73622. };
  73623. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  73624. this._selectionContent.reset();
  73625. for (var index = 0; index < this.blocks.length; index++) {
  73626. var block = this.blocks[index];
  73627. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  73628. }
  73629. if (allowDuplicate) {
  73630. this._selectionContent.concat(this.dynamicContent);
  73631. }
  73632. else {
  73633. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73634. }
  73635. return this._selectionContent;
  73636. };
  73637. Octree.prototype.intersectsRay = function (ray) {
  73638. this._selectionContent.reset();
  73639. for (var index = 0; index < this.blocks.length; index++) {
  73640. var block = this.blocks[index];
  73641. block.intersectsRay(ray, this._selectionContent);
  73642. }
  73643. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  73644. return this._selectionContent;
  73645. };
  73646. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  73647. target.blocks = new Array();
  73648. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  73649. // Segmenting space
  73650. for (var x = 0; x < 2; x++) {
  73651. for (var y = 0; y < 2; y++) {
  73652. for (var z = 0; z < 2; z++) {
  73653. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  73654. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  73655. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  73656. block.addEntries(entries);
  73657. target.blocks.push(block);
  73658. }
  73659. }
  73660. }
  73661. };
  73662. Octree.CreationFuncForMeshes = function (entry, block) {
  73663. var boundingInfo = entry.getBoundingInfo();
  73664. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73665. block.entries.push(entry);
  73666. }
  73667. };
  73668. Octree.CreationFuncForSubMeshes = function (entry, block) {
  73669. var boundingInfo = entry.getBoundingInfo();
  73670. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  73671. block.entries.push(entry);
  73672. }
  73673. };
  73674. return Octree;
  73675. }());
  73676. BABYLON.Octree = Octree;
  73677. })(BABYLON || (BABYLON = {}));
  73678. //# sourceMappingURL=babylon.octree.js.map
  73679. var BABYLON;
  73680. (function (BABYLON) {
  73681. var OctreeBlock = /** @class */ (function () {
  73682. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  73683. this.entries = new Array();
  73684. this._boundingVectors = new Array();
  73685. this._capacity = capacity;
  73686. this._depth = depth;
  73687. this._maxDepth = maxDepth;
  73688. this._creationFunc = creationFunc;
  73689. this._minPoint = minPoint;
  73690. this._maxPoint = maxPoint;
  73691. this._boundingVectors.push(minPoint.clone());
  73692. this._boundingVectors.push(maxPoint.clone());
  73693. this._boundingVectors.push(minPoint.clone());
  73694. this._boundingVectors[2].x = maxPoint.x;
  73695. this._boundingVectors.push(minPoint.clone());
  73696. this._boundingVectors[3].y = maxPoint.y;
  73697. this._boundingVectors.push(minPoint.clone());
  73698. this._boundingVectors[4].z = maxPoint.z;
  73699. this._boundingVectors.push(maxPoint.clone());
  73700. this._boundingVectors[5].z = minPoint.z;
  73701. this._boundingVectors.push(maxPoint.clone());
  73702. this._boundingVectors[6].x = minPoint.x;
  73703. this._boundingVectors.push(maxPoint.clone());
  73704. this._boundingVectors[7].y = minPoint.y;
  73705. }
  73706. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  73707. // Property
  73708. get: function () {
  73709. return this._capacity;
  73710. },
  73711. enumerable: true,
  73712. configurable: true
  73713. });
  73714. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  73715. get: function () {
  73716. return this._minPoint;
  73717. },
  73718. enumerable: true,
  73719. configurable: true
  73720. });
  73721. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  73722. get: function () {
  73723. return this._maxPoint;
  73724. },
  73725. enumerable: true,
  73726. configurable: true
  73727. });
  73728. // Methods
  73729. OctreeBlock.prototype.addEntry = function (entry) {
  73730. if (this.blocks) {
  73731. for (var index = 0; index < this.blocks.length; index++) {
  73732. var block = this.blocks[index];
  73733. block.addEntry(entry);
  73734. }
  73735. return;
  73736. }
  73737. this._creationFunc(entry, this);
  73738. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  73739. this.createInnerBlocks();
  73740. }
  73741. };
  73742. OctreeBlock.prototype.addEntries = function (entries) {
  73743. for (var index = 0; index < entries.length; index++) {
  73744. var mesh = entries[index];
  73745. this.addEntry(mesh);
  73746. }
  73747. };
  73748. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  73749. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  73750. if (this.blocks) {
  73751. for (var index = 0; index < this.blocks.length; index++) {
  73752. var block = this.blocks[index];
  73753. block.select(frustumPlanes, selection, allowDuplicate);
  73754. }
  73755. return;
  73756. }
  73757. if (allowDuplicate) {
  73758. selection.concat(this.entries);
  73759. }
  73760. else {
  73761. selection.concatWithNoDuplicate(this.entries);
  73762. }
  73763. }
  73764. };
  73765. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  73766. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  73767. if (this.blocks) {
  73768. for (var index = 0; index < this.blocks.length; index++) {
  73769. var block = this.blocks[index];
  73770. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  73771. }
  73772. return;
  73773. }
  73774. if (allowDuplicate) {
  73775. selection.concat(this.entries);
  73776. }
  73777. else {
  73778. selection.concatWithNoDuplicate(this.entries);
  73779. }
  73780. }
  73781. };
  73782. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  73783. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  73784. if (this.blocks) {
  73785. for (var index = 0; index < this.blocks.length; index++) {
  73786. var block = this.blocks[index];
  73787. block.intersectsRay(ray, selection);
  73788. }
  73789. return;
  73790. }
  73791. selection.concatWithNoDuplicate(this.entries);
  73792. }
  73793. };
  73794. OctreeBlock.prototype.createInnerBlocks = function () {
  73795. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  73796. };
  73797. return OctreeBlock;
  73798. }());
  73799. BABYLON.OctreeBlock = OctreeBlock;
  73800. })(BABYLON || (BABYLON = {}));
  73801. //# sourceMappingURL=babylon.octreeBlock.js.map
  73802. var BABYLON;
  73803. (function (BABYLON) {
  73804. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  73805. __extends(VRDistortionCorrectionPostProcess, _super);
  73806. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  73807. var _this = _super.call(this, name, "vrDistortionCorrection", [
  73808. 'LensCenter',
  73809. 'Scale',
  73810. 'ScaleIn',
  73811. 'HmdWarpParam'
  73812. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  73813. _this._isRightEye = isRightEye;
  73814. _this._distortionFactors = vrMetrics.distortionK;
  73815. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  73816. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  73817. _this.adaptScaleToCurrentViewport = true;
  73818. _this.onSizeChangedObservable.add(function () {
  73819. _this.aspectRatio = _this.width * .5 / _this.height;
  73820. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  73821. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  73822. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  73823. });
  73824. _this.onApplyObservable.add(function (effect) {
  73825. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  73826. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  73827. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  73828. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  73829. });
  73830. return _this;
  73831. }
  73832. return VRDistortionCorrectionPostProcess;
  73833. }(BABYLON.PostProcess));
  73834. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  73835. })(BABYLON || (BABYLON = {}));
  73836. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  73837. var BABYLON;
  73838. (function (BABYLON) {
  73839. var AnaglyphPostProcess = /** @class */ (function (_super) {
  73840. __extends(AnaglyphPostProcess, _super);
  73841. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  73842. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  73843. _this._passedProcess = rigCameras[0]._rigPostProcess;
  73844. _this.onApplyObservable.add(function (effect) {
  73845. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  73846. });
  73847. return _this;
  73848. }
  73849. return AnaglyphPostProcess;
  73850. }(BABYLON.PostProcess));
  73851. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  73852. })(BABYLON || (BABYLON = {}));
  73853. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  73854. var BABYLON;
  73855. (function (BABYLON) {
  73856. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  73857. __extends(StereoscopicInterlacePostProcess, _super);
  73858. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  73859. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  73860. _this._passedProcess = rigCameras[0]._rigPostProcess;
  73861. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  73862. _this.onSizeChangedObservable.add(function () {
  73863. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  73864. });
  73865. _this.onApplyObservable.add(function (effect) {
  73866. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  73867. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  73868. });
  73869. return _this;
  73870. }
  73871. return StereoscopicInterlacePostProcess;
  73872. }(BABYLON.PostProcess));
  73873. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  73874. })(BABYLON || (BABYLON = {}));
  73875. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  73876. var BABYLON;
  73877. (function (BABYLON) {
  73878. /**
  73879. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  73880. * Screen rotation is taken into account.
  73881. */
  73882. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  73883. function FreeCameraDeviceOrientationInput() {
  73884. var _this = this;
  73885. this._screenOrientationAngle = 0;
  73886. this._screenQuaternion = new BABYLON.Quaternion();
  73887. this._alpha = 0;
  73888. this._beta = 0;
  73889. this._gamma = 0;
  73890. this._orientationChanged = function () {
  73891. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  73892. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  73893. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  73894. };
  73895. this._deviceOrientation = function (evt) {
  73896. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  73897. _this._beta = evt.beta !== null ? evt.beta : 0;
  73898. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  73899. };
  73900. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  73901. this._orientationChanged();
  73902. }
  73903. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  73904. get: function () {
  73905. return this._camera;
  73906. },
  73907. set: function (camera) {
  73908. this._camera = camera;
  73909. if (this._camera != null && !this._camera.rotationQuaternion) {
  73910. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  73911. }
  73912. },
  73913. enumerable: true,
  73914. configurable: true
  73915. });
  73916. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  73917. window.addEventListener("orientationchange", this._orientationChanged);
  73918. window.addEventListener("deviceorientation", this._deviceOrientation);
  73919. //In certain cases, the attach control is called AFTER orientation was changed,
  73920. //So this is needed.
  73921. this._orientationChanged();
  73922. };
  73923. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  73924. window.removeEventListener("orientationchange", this._orientationChanged);
  73925. window.removeEventListener("deviceorientation", this._deviceOrientation);
  73926. };
  73927. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  73928. //if no device orientation provided, don't update the rotation.
  73929. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  73930. if (!this._alpha)
  73931. return;
  73932. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  73933. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  73934. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  73935. //Mirror on XY Plane
  73936. this._camera.rotationQuaternion.z *= -1;
  73937. this._camera.rotationQuaternion.w *= -1;
  73938. };
  73939. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  73940. return "FreeCameraDeviceOrientationInput";
  73941. };
  73942. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  73943. return "deviceOrientation";
  73944. };
  73945. return FreeCameraDeviceOrientationInput;
  73946. }());
  73947. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  73948. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  73949. })(BABYLON || (BABYLON = {}));
  73950. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  73951. var BABYLON;
  73952. (function (BABYLON) {
  73953. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  73954. function ArcRotateCameraVRDeviceOrientationInput() {
  73955. this.alphaCorrection = 1;
  73956. this.betaCorrection = 1;
  73957. this.gammaCorrection = 1;
  73958. this._alpha = 0;
  73959. this._gamma = 0;
  73960. this._dirty = false;
  73961. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  73962. }
  73963. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  73964. this.camera.attachControl(element, noPreventDefault);
  73965. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  73966. };
  73967. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  73968. if (evt.alpha !== null) {
  73969. this._alpha = +evt.alpha | 0;
  73970. }
  73971. if (evt.gamma !== null) {
  73972. this._gamma = +evt.gamma | 0;
  73973. }
  73974. this._dirty = true;
  73975. };
  73976. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  73977. if (this._dirty) {
  73978. this._dirty = false;
  73979. if (this._gamma < 0) {
  73980. this._gamma = 180 + this._gamma;
  73981. }
  73982. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  73983. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  73984. }
  73985. };
  73986. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  73987. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  73988. };
  73989. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  73990. return "ArcRotateCameraVRDeviceOrientationInput";
  73991. };
  73992. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  73993. return "VRDeviceOrientation";
  73994. };
  73995. return ArcRotateCameraVRDeviceOrientationInput;
  73996. }());
  73997. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  73998. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  73999. })(BABYLON || (BABYLON = {}));
  74000. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74001. var BABYLON;
  74002. (function (BABYLON) {
  74003. var VRCameraMetrics = /** @class */ (function () {
  74004. function VRCameraMetrics() {
  74005. this.compensateDistortion = true;
  74006. }
  74007. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74008. get: function () {
  74009. return this.hResolution / (2 * this.vResolution);
  74010. },
  74011. enumerable: true,
  74012. configurable: true
  74013. });
  74014. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74015. get: function () {
  74016. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74017. },
  74018. enumerable: true,
  74019. configurable: true
  74020. });
  74021. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74022. get: function () {
  74023. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74024. var h = (4 * meters) / this.hScreenSize;
  74025. return BABYLON.Matrix.Translation(h, 0, 0);
  74026. },
  74027. enumerable: true,
  74028. configurable: true
  74029. });
  74030. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74031. get: function () {
  74032. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74033. var h = (4 * meters) / this.hScreenSize;
  74034. return BABYLON.Matrix.Translation(-h, 0, 0);
  74035. },
  74036. enumerable: true,
  74037. configurable: true
  74038. });
  74039. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74040. get: function () {
  74041. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74042. },
  74043. enumerable: true,
  74044. configurable: true
  74045. });
  74046. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74047. get: function () {
  74048. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74049. },
  74050. enumerable: true,
  74051. configurable: true
  74052. });
  74053. VRCameraMetrics.GetDefault = function () {
  74054. var result = new VRCameraMetrics();
  74055. result.hResolution = 1280;
  74056. result.vResolution = 800;
  74057. result.hScreenSize = 0.149759993;
  74058. result.vScreenSize = 0.0935999975;
  74059. result.vScreenCenter = 0.0467999987;
  74060. result.eyeToScreenDistance = 0.0410000011;
  74061. result.lensSeparationDistance = 0.0635000020;
  74062. result.interpupillaryDistance = 0.0640000030;
  74063. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74064. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74065. result.postProcessScaleFactor = 1.714605507808412;
  74066. result.lensCenterOffset = 0.151976421;
  74067. return result;
  74068. };
  74069. return VRCameraMetrics;
  74070. }());
  74071. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74072. })(BABYLON || (BABYLON = {}));
  74073. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74074. var BABYLON;
  74075. (function (BABYLON) {
  74076. var WebVRFreeCamera = /** @class */ (function (_super) {
  74077. __extends(WebVRFreeCamera, _super);
  74078. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74079. if (webVROptions === void 0) { webVROptions = {}; }
  74080. var _this = _super.call(this, name, position, scene) || this;
  74081. _this.webVROptions = webVROptions;
  74082. _this._vrDevice = null;
  74083. _this.rawPose = null;
  74084. _this._specsVersion = "1.1";
  74085. _this._attached = false;
  74086. _this._descendants = [];
  74087. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74088. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74089. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74090. _this._standingMatrix = null;
  74091. // Represents device position and rotation in babylon space
  74092. _this.devicePosition = BABYLON.Vector3.Zero();
  74093. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74094. _this.deviceScaleFactor = 1;
  74095. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74096. _this._worldToDevice = BABYLON.Matrix.Identity();
  74097. _this.controllers = [];
  74098. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74099. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74100. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  74101. _this._defaultHeight = undefined;
  74102. _this.deviceDistanceToRoomGround = function () {
  74103. if (_this._standingMatrix && _this._defaultHeight === undefined) {
  74104. // Add standing matrix offset to get real offset from ground in room
  74105. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  74106. return _this._deviceRoomPosition.y + _this._workingVector.y;
  74107. }
  74108. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74109. return _this._defaultHeight || 0;
  74110. };
  74111. _this.useStandingMatrix = function (callback) {
  74112. if (callback === void 0) { callback = function (bool) { }; }
  74113. // Use standing matrix if availible
  74114. if (!navigator || !navigator.getVRDisplays) {
  74115. callback(false);
  74116. }
  74117. else {
  74118. navigator.getVRDisplays().then(function (displays) {
  74119. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  74120. callback(false);
  74121. }
  74122. else {
  74123. _this._standingMatrix = new BABYLON.Matrix();
  74124. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  74125. if (!_this.getScene().useRightHandedSystem) {
  74126. [2, 6, 8, 9, 14].forEach(function (num) {
  74127. if (_this._standingMatrix) {
  74128. _this._standingMatrix.m[num] *= -1;
  74129. }
  74130. });
  74131. }
  74132. callback(true);
  74133. }
  74134. });
  74135. }
  74136. };
  74137. _this._workingVector = BABYLON.Vector3.Zero();
  74138. _this._oneVector = BABYLON.Vector3.One();
  74139. _this._workingMatrix = BABYLON.Matrix.Identity();
  74140. _this._cache.position = BABYLON.Vector3.Zero();
  74141. if (webVROptions.defaultHeight) {
  74142. _this._defaultHeight = webVROptions.defaultHeight;
  74143. _this.position.y = _this._defaultHeight;
  74144. }
  74145. _this.minZ = 0.1;
  74146. //legacy support - the compensation boolean was removed.
  74147. if (arguments.length === 5) {
  74148. _this.webVROptions = arguments[4];
  74149. }
  74150. // default webVR options
  74151. if (_this.webVROptions.trackPosition == undefined) {
  74152. _this.webVROptions.trackPosition = true;
  74153. }
  74154. if (_this.webVROptions.controllerMeshes == undefined) {
  74155. _this.webVROptions.controllerMeshes = true;
  74156. }
  74157. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74158. _this.webVROptions.defaultLightingOnControllers = true;
  74159. }
  74160. _this.rotationQuaternion = new BABYLON.Quaternion();
  74161. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74162. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74163. }
  74164. //enable VR
  74165. var engine = _this.getEngine();
  74166. _this._onVREnabled = function (success) { if (success) {
  74167. _this.initControllers();
  74168. } };
  74169. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74170. engine.initWebVR().add(function (event) {
  74171. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74172. return;
  74173. }
  74174. _this._vrDevice = event.vrDisplay;
  74175. //reset the rig parameters.
  74176. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74177. if (_this._attached) {
  74178. _this.getEngine().enableVR();
  74179. }
  74180. });
  74181. if (typeof (VRFrameData) !== "undefined")
  74182. _this._frameData = new VRFrameData();
  74183. /**
  74184. * The idea behind the following lines:
  74185. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74186. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74187. * the second will not show it correctly.
  74188. *
  74189. * To solve this - each object that has the camera as parent will be added to a protected array.
  74190. * When the rig camera renders, it will take this array and set all of those to be its children.
  74191. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74192. * Amazing!
  74193. */
  74194. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74195. if (camera.parent === _this && _this.rigParenting) {
  74196. _this._descendants = _this.getDescendants(true, function (n) {
  74197. // don't take the cameras or the controllers!
  74198. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74199. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74200. return !isController && !isRigCamera;
  74201. });
  74202. _this._descendants.forEach(function (node) {
  74203. node.parent = camera;
  74204. });
  74205. }
  74206. });
  74207. scene.onAfterCameraRenderObservable.add(function (camera) {
  74208. if (camera.parent === _this && _this.rigParenting) {
  74209. _this._descendants.forEach(function (node) {
  74210. node.parent = _this;
  74211. });
  74212. }
  74213. });
  74214. return _this;
  74215. }
  74216. WebVRFreeCamera.prototype.dispose = function () {
  74217. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  74218. _super.prototype.dispose.call(this);
  74219. };
  74220. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  74221. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  74222. var gp = _a[_i];
  74223. if (gp.hand === name) {
  74224. return gp;
  74225. }
  74226. }
  74227. return null;
  74228. };
  74229. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  74230. get: function () {
  74231. if (!this._leftController) {
  74232. this._leftController = this.getControllerByName("left");
  74233. }
  74234. return this._leftController;
  74235. },
  74236. enumerable: true,
  74237. configurable: true
  74238. });
  74239. ;
  74240. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  74241. get: function () {
  74242. if (!this._rightController) {
  74243. this._rightController = this.getControllerByName("right");
  74244. }
  74245. return this._rightController;
  74246. },
  74247. enumerable: true,
  74248. configurable: true
  74249. });
  74250. ;
  74251. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  74252. if (length === void 0) { length = 100; }
  74253. if (this.leftCamera) {
  74254. // Use left eye to avoid computation to compute center on every call
  74255. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  74256. }
  74257. else {
  74258. return _super.prototype.getForwardRay.call(this, length);
  74259. }
  74260. };
  74261. WebVRFreeCamera.prototype._checkInputs = function () {
  74262. if (this._vrDevice && this._vrDevice.isPresenting) {
  74263. this._vrDevice.getFrameData(this._frameData);
  74264. this.updateFromDevice(this._frameData.pose);
  74265. }
  74266. _super.prototype._checkInputs.call(this);
  74267. };
  74268. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  74269. if (poseData && poseData.orientation) {
  74270. this.rawPose = poseData;
  74271. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  74272. if (this.getScene().useRightHandedSystem) {
  74273. this._deviceRoomRotationQuaternion.z *= -1;
  74274. this._deviceRoomRotationQuaternion.w *= -1;
  74275. }
  74276. if (this.webVROptions.trackPosition && this.rawPose.position) {
  74277. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  74278. if (this.getScene().useRightHandedSystem) {
  74279. this._deviceRoomPosition.z *= -1;
  74280. }
  74281. }
  74282. }
  74283. };
  74284. /**
  74285. * WebVR's attach control will start broadcasting frames to the device.
  74286. * Note that in certain browsers (chrome for example) this function must be called
  74287. * within a user-interaction callback. Example:
  74288. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  74289. *
  74290. * @param {HTMLElement} element
  74291. * @param {boolean} [noPreventDefault]
  74292. *
  74293. * @memberOf WebVRFreeCamera
  74294. */
  74295. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  74296. _super.prototype.attachControl.call(this, element, noPreventDefault);
  74297. this._attached = true;
  74298. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  74299. if (this._vrDevice) {
  74300. this.getEngine().enableVR();
  74301. }
  74302. };
  74303. WebVRFreeCamera.prototype.detachControl = function (element) {
  74304. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74305. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74306. _super.prototype.detachControl.call(this, element);
  74307. this._attached = false;
  74308. this.getEngine().disableVR();
  74309. };
  74310. WebVRFreeCamera.prototype.getClassName = function () {
  74311. return "WebVRFreeCamera";
  74312. };
  74313. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  74314. //uses the vrDisplay's "resetPose()".
  74315. //pitch and roll won't be affected.
  74316. this._vrDevice.resetPose();
  74317. };
  74318. WebVRFreeCamera.prototype._updateRigCameras = function () {
  74319. var camLeft = this._rigCameras[0];
  74320. var camRight = this._rigCameras[1];
  74321. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74322. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74323. camLeft.position.copyFrom(this._deviceRoomPosition);
  74324. camRight.position.copyFrom(this._deviceRoomPosition);
  74325. };
  74326. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  74327. var _this = this;
  74328. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  74329. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  74330. if (!this.updateCacheCalled) {
  74331. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  74332. this.updateCacheCalled = true;
  74333. this.update();
  74334. }
  74335. // Set working vector to the device position in room space rotated by the new rotation
  74336. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  74337. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  74338. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  74339. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  74340. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  74341. // Add translation from anchor position
  74342. this._deviceToWorld.getTranslationToRef(this._workingVector);
  74343. this._workingVector.addInPlace(this.position);
  74344. this._workingVector.subtractInPlace(this._cache.position);
  74345. this._deviceToWorld.setTranslation(this._workingVector);
  74346. // Set an inverted matrix to be used when updating the camera
  74347. this._deviceToWorld.invertToRef(this._worldToDevice);
  74348. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  74349. this.controllers.forEach(function (controller) {
  74350. controller._deviceToWorld = _this._deviceToWorld;
  74351. controller.update();
  74352. });
  74353. }
  74354. if (!ignoreParentClass) {
  74355. _super.prototype._updateCache.call(this);
  74356. }
  74357. this.updateCacheCalled = false;
  74358. };
  74359. WebVRFreeCamera.prototype.update = function () {
  74360. // Get current device position in babylon world
  74361. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  74362. // Get current device rotation in babylon world
  74363. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  74364. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  74365. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74366. _super.prototype.update.call(this);
  74367. };
  74368. WebVRFreeCamera.prototype._getViewMatrix = function () {
  74369. return BABYLON.Matrix.Identity();
  74370. };
  74371. /**
  74372. * This function is called by the two RIG cameras.
  74373. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  74374. */
  74375. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  74376. var _this = this;
  74377. //WebVR 1.1
  74378. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  74379. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  74380. if (!this.getScene().useRightHandedSystem) {
  74381. [2, 6, 8, 9, 14].forEach(function (num) {
  74382. _this._webvrViewMatrix.m[num] *= -1;
  74383. });
  74384. }
  74385. // update the camera rotation matrix
  74386. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  74387. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  74388. // Computing target and final matrix
  74389. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  74390. var parentCamera = this._cameraRigParams["parentCamera"];
  74391. // should the view matrix be updated with scale and position offset?
  74392. if (parentCamera.deviceScaleFactor !== 1) {
  74393. this._webvrViewMatrix.invert();
  74394. // scale the position, if set
  74395. if (parentCamera.deviceScaleFactor) {
  74396. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  74397. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  74398. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  74399. }
  74400. this._webvrViewMatrix.invert();
  74401. }
  74402. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  74403. return this._webvrViewMatrix;
  74404. };
  74405. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  74406. var _this = this;
  74407. var parentCamera = this.parent;
  74408. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  74409. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  74410. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  74411. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  74412. //babylon compatible matrix
  74413. if (!this.getScene().useRightHandedSystem) {
  74414. [8, 9, 10, 11].forEach(function (num) {
  74415. _this._projectionMatrix.m[num] *= -1;
  74416. });
  74417. }
  74418. return this._projectionMatrix;
  74419. };
  74420. WebVRFreeCamera.prototype.initControllers = function () {
  74421. var _this = this;
  74422. this.controllers = [];
  74423. var manager = this.getScene().gamepadManager;
  74424. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74425. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74426. var webVrController = gamepad;
  74427. if (webVrController.defaultModel) {
  74428. webVrController.defaultModel.setEnabled(false);
  74429. }
  74430. if (webVrController.hand === "right") {
  74431. _this._rightController = null;
  74432. }
  74433. if (webVrController.hand === "left") {
  74434. _this._rightController = null;
  74435. }
  74436. var controllerIndex = _this.controllers.indexOf(webVrController);
  74437. if (controllerIndex !== -1) {
  74438. _this.controllers.splice(controllerIndex, 1);
  74439. }
  74440. }
  74441. });
  74442. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74443. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74444. var webVrController_1 = gamepad;
  74445. webVrController_1._deviceToWorld = _this._deviceToWorld;
  74446. if (_this.webVROptions.controllerMeshes) {
  74447. if (webVrController_1.defaultModel) {
  74448. webVrController_1.defaultModel.setEnabled(true);
  74449. }
  74450. else {
  74451. // Load the meshes
  74452. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  74453. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  74454. if (_this.webVROptions.defaultLightingOnControllers) {
  74455. if (!_this._lightOnControllers) {
  74456. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  74457. }
  74458. var activateLightOnSubMeshes_1 = function (mesh, light) {
  74459. var children = mesh.getChildren();
  74460. if (children.length !== 0) {
  74461. children.forEach(function (mesh) {
  74462. light.includedOnlyMeshes.push(mesh);
  74463. activateLightOnSubMeshes_1(mesh, light);
  74464. });
  74465. }
  74466. };
  74467. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  74468. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  74469. }
  74470. });
  74471. }
  74472. }
  74473. webVrController_1.attachToPoseControlledCamera(_this);
  74474. // since this is async - sanity check. Is the controller already stored?
  74475. if (_this.controllers.indexOf(webVrController_1) === -1) {
  74476. //add to the controllers array
  74477. _this.controllers.push(webVrController_1);
  74478. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  74479. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  74480. // So we're overriding setting left & right manually to be sure
  74481. var firstViveWandDetected = false;
  74482. for (var i = 0; i < _this.controllers.length; i++) {
  74483. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74484. if (!firstViveWandDetected) {
  74485. firstViveWandDetected = true;
  74486. _this.controllers[i].hand = "left";
  74487. }
  74488. else {
  74489. _this.controllers[i].hand = "right";
  74490. }
  74491. }
  74492. }
  74493. //did we find enough controllers? Great! let the developer know.
  74494. if (_this.controllers.length >= 2) {
  74495. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  74496. }
  74497. }
  74498. }
  74499. });
  74500. };
  74501. return WebVRFreeCamera;
  74502. }(BABYLON.FreeCamera));
  74503. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  74504. })(BABYLON || (BABYLON = {}));
  74505. //# sourceMappingURL=babylon.webVRCamera.js.map
  74506. var BABYLON;
  74507. (function (BABYLON) {
  74508. // We're mainly based on the logic defined into the FreeCamera code
  74509. /**
  74510. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  74511. * being tilted forward or back and left or right.
  74512. */
  74513. var DeviceOrientationCamera = /** @class */ (function (_super) {
  74514. __extends(DeviceOrientationCamera, _super);
  74515. /**
  74516. * Creates a new device orientation camera. @see DeviceOrientationCamera
  74517. * @param name The name of the camera
  74518. * @param position The start position camera
  74519. * @param scene The scene the camera belongs to
  74520. */
  74521. function DeviceOrientationCamera(name, position, scene) {
  74522. var _this = _super.call(this, name, position, scene) || this;
  74523. _this._quaternionCache = new BABYLON.Quaternion();
  74524. _this.inputs.addDeviceOrientation();
  74525. return _this;
  74526. }
  74527. /**
  74528. * Gets the current instance class name ("DeviceOrientationCamera").
  74529. * This helps avoiding instanceof at run time.
  74530. * @returns the class name
  74531. */
  74532. DeviceOrientationCamera.prototype.getClassName = function () {
  74533. return "DeviceOrientationCamera";
  74534. };
  74535. /**
  74536. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  74537. */
  74538. DeviceOrientationCamera.prototype._checkInputs = function () {
  74539. _super.prototype._checkInputs.call(this);
  74540. this._quaternionCache.copyFrom(this.rotationQuaternion);
  74541. if (this._initialQuaternion) {
  74542. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74543. }
  74544. };
  74545. /**
  74546. * Reset the camera to its default orientation on the specified axis only.
  74547. * @param axis The axis to reset
  74548. */
  74549. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  74550. var _this = this;
  74551. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  74552. //can only work if this camera has a rotation quaternion already.
  74553. if (!this.rotationQuaternion)
  74554. return;
  74555. if (!this._initialQuaternion) {
  74556. this._initialQuaternion = new BABYLON.Quaternion();
  74557. }
  74558. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  74559. ['x', 'y', 'z'].forEach(function (axisName) {
  74560. if (!axis[axisName]) {
  74561. _this._initialQuaternion[axisName] = 0;
  74562. }
  74563. else {
  74564. _this._initialQuaternion[axisName] *= -1;
  74565. }
  74566. });
  74567. this._initialQuaternion.normalize();
  74568. //force rotation update
  74569. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  74570. };
  74571. return DeviceOrientationCamera;
  74572. }(BABYLON.FreeCamera));
  74573. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  74574. })(BABYLON || (BABYLON = {}));
  74575. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  74576. var BABYLON;
  74577. (function (BABYLON) {
  74578. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  74579. __extends(VRDeviceOrientationFreeCamera, _super);
  74580. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74581. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74582. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74583. var _this = _super.call(this, name, position, scene) || this;
  74584. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74585. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74586. return _this;
  74587. }
  74588. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  74589. return "VRDeviceOrientationFreeCamera";
  74590. };
  74591. return VRDeviceOrientationFreeCamera;
  74592. }(BABYLON.DeviceOrientationCamera));
  74593. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  74594. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  74595. __extends(VRDeviceOrientationGamepadCamera, _super);
  74596. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  74597. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74598. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74599. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  74600. _this.inputs.addGamepad();
  74601. return _this;
  74602. }
  74603. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  74604. return "VRDeviceOrientationGamepadCamera";
  74605. };
  74606. return VRDeviceOrientationGamepadCamera;
  74607. }(VRDeviceOrientationFreeCamera));
  74608. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  74609. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  74610. __extends(VRDeviceOrientationArcRotateCamera, _super);
  74611. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  74612. if (compensateDistortion === void 0) { compensateDistortion = true; }
  74613. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  74614. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74615. vrCameraMetrics.compensateDistortion = compensateDistortion;
  74616. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  74617. _this.inputs.addVRDeviceOrientation();
  74618. return _this;
  74619. }
  74620. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  74621. return "VRDeviceOrientationArcRotateCamera";
  74622. };
  74623. return VRDeviceOrientationArcRotateCamera;
  74624. }(BABYLON.ArcRotateCamera));
  74625. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  74626. })(BABYLON || (BABYLON = {}));
  74627. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  74628. var BABYLON;
  74629. (function (BABYLON) {
  74630. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  74631. __extends(AnaglyphFreeCamera, _super);
  74632. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  74633. var _this = _super.call(this, name, position, scene) || this;
  74634. _this.interaxialDistance = interaxialDistance;
  74635. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74636. return _this;
  74637. }
  74638. AnaglyphFreeCamera.prototype.getClassName = function () {
  74639. return "AnaglyphFreeCamera";
  74640. };
  74641. return AnaglyphFreeCamera;
  74642. }(BABYLON.FreeCamera));
  74643. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  74644. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  74645. __extends(AnaglyphArcRotateCamera, _super);
  74646. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  74647. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74648. _this.interaxialDistance = interaxialDistance;
  74649. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74650. return _this;
  74651. }
  74652. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  74653. return "AnaglyphArcRotateCamera";
  74654. };
  74655. return AnaglyphArcRotateCamera;
  74656. }(BABYLON.ArcRotateCamera));
  74657. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  74658. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  74659. __extends(AnaglyphGamepadCamera, _super);
  74660. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  74661. var _this = _super.call(this, name, position, scene) || this;
  74662. _this.interaxialDistance = interaxialDistance;
  74663. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74664. return _this;
  74665. }
  74666. AnaglyphGamepadCamera.prototype.getClassName = function () {
  74667. return "AnaglyphGamepadCamera";
  74668. };
  74669. return AnaglyphGamepadCamera;
  74670. }(BABYLON.GamepadCamera));
  74671. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  74672. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  74673. __extends(AnaglyphUniversalCamera, _super);
  74674. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  74675. var _this = _super.call(this, name, position, scene) || this;
  74676. _this.interaxialDistance = interaxialDistance;
  74677. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  74678. return _this;
  74679. }
  74680. AnaglyphUniversalCamera.prototype.getClassName = function () {
  74681. return "AnaglyphUniversalCamera";
  74682. };
  74683. return AnaglyphUniversalCamera;
  74684. }(BABYLON.UniversalCamera));
  74685. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  74686. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  74687. __extends(StereoscopicFreeCamera, _super);
  74688. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74689. var _this = _super.call(this, name, position, scene) || this;
  74690. _this.interaxialDistance = interaxialDistance;
  74691. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74692. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74693. return _this;
  74694. }
  74695. StereoscopicFreeCamera.prototype.getClassName = function () {
  74696. return "StereoscopicFreeCamera";
  74697. };
  74698. return StereoscopicFreeCamera;
  74699. }(BABYLON.FreeCamera));
  74700. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  74701. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  74702. __extends(StereoscopicArcRotateCamera, _super);
  74703. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  74704. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  74705. _this.interaxialDistance = interaxialDistance;
  74706. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74707. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74708. return _this;
  74709. }
  74710. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  74711. return "StereoscopicArcRotateCamera";
  74712. };
  74713. return StereoscopicArcRotateCamera;
  74714. }(BABYLON.ArcRotateCamera));
  74715. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  74716. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  74717. __extends(StereoscopicGamepadCamera, _super);
  74718. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74719. var _this = _super.call(this, name, position, scene) || this;
  74720. _this.interaxialDistance = interaxialDistance;
  74721. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74722. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74723. return _this;
  74724. }
  74725. StereoscopicGamepadCamera.prototype.getClassName = function () {
  74726. return "StereoscopicGamepadCamera";
  74727. };
  74728. return StereoscopicGamepadCamera;
  74729. }(BABYLON.GamepadCamera));
  74730. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  74731. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  74732. __extends(StereoscopicUniversalCamera, _super);
  74733. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  74734. var _this = _super.call(this, name, position, scene) || this;
  74735. _this.interaxialDistance = interaxialDistance;
  74736. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  74737. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  74738. return _this;
  74739. }
  74740. StereoscopicUniversalCamera.prototype.getClassName = function () {
  74741. return "StereoscopicUniversalCamera";
  74742. };
  74743. return StereoscopicUniversalCamera;
  74744. }(BABYLON.UniversalCamera));
  74745. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  74746. })(BABYLON || (BABYLON = {}));
  74747. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  74748. var BABYLON;
  74749. (function (BABYLON) {
  74750. var VRExperienceHelper = /** @class */ (function () {
  74751. function VRExperienceHelper(scene, webVROptions) {
  74752. if (webVROptions === void 0) { webVROptions = {}; }
  74753. var _this = this;
  74754. this.webVROptions = webVROptions;
  74755. // Can the system support WebVR, even if a headset isn't plugged in?
  74756. this._webVRsupported = false;
  74757. // If WebVR is supported, is a headset plugged in and are we ready to present?
  74758. this._webVRready = false;
  74759. // Are we waiting for the requestPresent callback to complete?
  74760. this._webVRrequesting = false;
  74761. // Are we presenting to the headset right now?
  74762. this._webVRpresenting = false;
  74763. // Are we presenting in the fullscreen fallback?
  74764. this._fullscreenVRpresenting = false;
  74765. /**
  74766. * Observable raised when entering VR.
  74767. */
  74768. this.onEnteringVRObservable = new BABYLON.Observable();
  74769. /**
  74770. * Observable raised when exiting VR.
  74771. */
  74772. this.onExitingVRObservable = new BABYLON.Observable();
  74773. /**
  74774. * Observable raised when controller mesh is loaded.
  74775. */
  74776. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74777. this._useCustomVRButton = false;
  74778. this._teleportationRequested = false;
  74779. this._teleportationEnabledOnLeftController = false;
  74780. this._teleportationEnabledOnRightController = false;
  74781. this._interactionsEnabledOnLeftController = false;
  74782. this._interactionsEnabledOnRightController = false;
  74783. this._leftControllerReady = false;
  74784. this._rightControllerReady = false;
  74785. this._floorMeshesCollection = [];
  74786. this._teleportationAllowed = false;
  74787. this._rotationAllowed = true;
  74788. this._teleportationRequestInitiated = false;
  74789. this._teleportationBackRequestInitiated = false;
  74790. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  74791. this._rotationRightAsked = false;
  74792. this._rotationLeftAsked = false;
  74793. this._isDefaultTeleportationTarget = true;
  74794. this._teleportationFillColor = "#444444";
  74795. this._teleportationBorderColor = "#FFFFFF";
  74796. this._rotationAngle = 0;
  74797. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  74798. this._padSensibilityUp = 0.65;
  74799. this._padSensibilityDown = 0.35;
  74800. /**
  74801. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  74802. */
  74803. this.onNewMeshSelected = new BABYLON.Observable();
  74804. /**
  74805. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  74806. */
  74807. this.onNewMeshPicked = new BABYLON.Observable();
  74808. /**
  74809. * Observable raised before camera teleportation
  74810. */
  74811. this.onBeforeCameraTeleport = new BABYLON.Observable();
  74812. /**
  74813. * Observable raised after camera teleportation
  74814. */
  74815. this.onAfterCameraTeleport = new BABYLON.Observable();
  74816. /**
  74817. * Observable raised when current selected mesh gets unselected
  74818. */
  74819. this.onSelectedMeshUnselected = new BABYLON.Observable();
  74820. /**
  74821. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  74822. */
  74823. this.teleportationEnabled = true;
  74824. this._pointerDownOnMeshAsked = false;
  74825. this._isActionableMesh = false;
  74826. this._teleportationInitialized = false;
  74827. this._interactionsEnabled = false;
  74828. this._interactionsRequested = false;
  74829. this._displayGaze = true;
  74830. this._displayLaserPointer = true;
  74831. this._dpadPressed = true;
  74832. this._onResize = function () {
  74833. _this.moveButtonToBottomRight();
  74834. if (_this._fullscreenVRpresenting && _this._webVRready) {
  74835. _this.exitVR();
  74836. }
  74837. };
  74838. this._onFullscreenChange = function () {
  74839. if (document.fullscreen !== undefined) {
  74840. _this._fullscreenVRpresenting = document.fullscreen;
  74841. }
  74842. else if (document.mozFullScreen !== undefined) {
  74843. _this._fullscreenVRpresenting = document.mozFullScreen;
  74844. }
  74845. else if (document.webkitIsFullScreen !== undefined) {
  74846. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  74847. }
  74848. else if (document.msIsFullScreen !== undefined) {
  74849. _this._fullscreenVRpresenting = document.msIsFullScreen;
  74850. }
  74851. if (!_this._fullscreenVRpresenting && _this._canvas) {
  74852. _this.exitVR();
  74853. if (!_this._useCustomVRButton) {
  74854. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  74855. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  74856. }
  74857. }
  74858. };
  74859. this.beforeRender = function () {
  74860. _this._castRayAndSelectObject();
  74861. };
  74862. this._onNewGamepadConnected = function (gamepad) {
  74863. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  74864. if (gamepad.leftStick) {
  74865. gamepad.onleftstickchanged(function (stickValues) {
  74866. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  74867. // Listening to classic/xbox gamepad only if no VR controller is active
  74868. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  74869. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  74870. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  74871. _this._checkTeleportWithRay(stickValues);
  74872. _this._checkTeleportBackwards(stickValues);
  74873. }
  74874. }
  74875. });
  74876. }
  74877. if (gamepad.rightStick) {
  74878. gamepad.onrightstickchanged(function (stickValues) {
  74879. if (_this._teleportationInitialized) {
  74880. _this._checkRotate(stickValues);
  74881. }
  74882. });
  74883. }
  74884. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  74885. gamepad.onbuttondown(function (buttonPressed) {
  74886. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  74887. _this._selectionPointerDown();
  74888. }
  74889. });
  74890. gamepad.onbuttonup(function (buttonPressed) {
  74891. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  74892. _this._selectionPointerUp();
  74893. }
  74894. });
  74895. }
  74896. }
  74897. else {
  74898. var webVRController = gamepad;
  74899. _this._tryEnableInteractionOnController(webVRController);
  74900. }
  74901. };
  74902. // 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
  74903. this._tryEnableInteractionOnController = function (webVRController) {
  74904. if (webVRController.hand === "left") {
  74905. _this._leftControllerReady = true;
  74906. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  74907. _this._enableInteractionOnController(webVRController);
  74908. }
  74909. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  74910. _this._enableTeleportationOnController(webVRController);
  74911. }
  74912. }
  74913. if (webVRController.hand === "right") {
  74914. _this._rightControllerReady = true;
  74915. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  74916. _this._enableInteractionOnController(webVRController);
  74917. }
  74918. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  74919. _this._enableTeleportationOnController(webVRController);
  74920. }
  74921. }
  74922. };
  74923. this._onNewGamepadDisconnected = function (gamepad) {
  74924. if (gamepad instanceof BABYLON.WebVRController) {
  74925. if (gamepad.hand === "left") {
  74926. _this._interactionsEnabledOnLeftController = false;
  74927. _this._teleportationEnabledOnLeftController = false;
  74928. _this._leftControllerReady = false;
  74929. if (_this._leftLaserPointer) {
  74930. _this._leftLaserPointer.dispose();
  74931. }
  74932. }
  74933. if (gamepad.hand === "right") {
  74934. _this._interactionsEnabledOnRightController = false;
  74935. _this._teleportationEnabledOnRightController = false;
  74936. _this._rightControllerReady = false;
  74937. if (_this._rightLaserPointer) {
  74938. _this._rightLaserPointer.dispose();
  74939. }
  74940. }
  74941. }
  74942. };
  74943. this._workingVector = BABYLON.Vector3.Zero();
  74944. this._workingQuaternion = BABYLON.Quaternion.Identity();
  74945. this._workingMatrix = BABYLON.Matrix.Identity();
  74946. this._scene = scene;
  74947. this._canvas = scene.getEngine().getRenderingCanvas();
  74948. // Parse options
  74949. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  74950. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  74951. }
  74952. if (webVROptions.createDeviceOrientationCamera === undefined) {
  74953. webVROptions.createDeviceOrientationCamera = true;
  74954. }
  74955. if (webVROptions.defaultHeight === undefined) {
  74956. webVROptions.defaultHeight = 1.7;
  74957. }
  74958. if (webVROptions.useCustomVRButton) {
  74959. this._useCustomVRButton = true;
  74960. if (webVROptions.customVRButton) {
  74961. this._btnVR = webVROptions.customVRButton;
  74962. }
  74963. }
  74964. if (webVROptions.rayLength) {
  74965. this._rayLength = webVROptions.rayLength;
  74966. }
  74967. this._defaultHeight = webVROptions.defaultHeight;
  74968. // Set position
  74969. if (this._scene.activeCamera) {
  74970. this._position = this._scene.activeCamera.position.clone();
  74971. }
  74972. else {
  74973. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  74974. }
  74975. // Set non-vr camera
  74976. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  74977. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  74978. // Copy data from existing camera
  74979. if (this._scene.activeCamera) {
  74980. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  74981. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  74982. // Set rotation from previous camera
  74983. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  74984. var targetCamera = this._scene.activeCamera;
  74985. if (targetCamera.rotationQuaternion) {
  74986. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  74987. }
  74988. else {
  74989. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  74990. }
  74991. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  74992. }
  74993. }
  74994. this._scene.activeCamera = this._deviceOrientationCamera;
  74995. if (this._canvas) {
  74996. this._scene.activeCamera.attachControl(this._canvas);
  74997. }
  74998. }
  74999. else {
  75000. this._existingCamera = this._scene.activeCamera;
  75001. }
  75002. // Create VR cameras
  75003. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75004. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75005. }
  75006. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75007. this._webVRCamera.useStandingMatrix();
  75008. // Create default button
  75009. if (!this._useCustomVRButton) {
  75010. this._btnVR = document.createElement("BUTTON");
  75011. this._btnVR.className = "babylonVRicon";
  75012. this._btnVR.id = "babylonVRiconbtn";
  75013. this._btnVR.title = "Click to switch to VR";
  75014. 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) }";
  75015. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75016. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75017. // css += ".babylonVRicon.vrdisplaysupported { }";
  75018. // css += ".babylonVRicon.vrdisplayready { }";
  75019. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75020. var style = document.createElement('style');
  75021. style.appendChild(document.createTextNode(css));
  75022. document.getElementsByTagName('head')[0].appendChild(style);
  75023. this.moveButtonToBottomRight();
  75024. }
  75025. // VR button click event
  75026. if (this._btnVR) {
  75027. this._btnVR.addEventListener("click", function () {
  75028. if (!_this.isInVRMode) {
  75029. _this.enterVR();
  75030. }
  75031. else {
  75032. _this.exitVR();
  75033. }
  75034. });
  75035. }
  75036. // Window events
  75037. window.addEventListener("resize", this._onResize);
  75038. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75039. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75040. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75041. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75042. // Display vr button when headset is connected
  75043. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75044. this.displayVRButton();
  75045. }
  75046. else {
  75047. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75048. if (e.vrDisplay) {
  75049. _this.displayVRButton();
  75050. }
  75051. });
  75052. }
  75053. // Exiting VR mode using 'ESC' key on desktop
  75054. this._onKeyDown = function (event) {
  75055. if (event.keyCode === 27 && _this.isInVRMode) {
  75056. _this.exitVR();
  75057. }
  75058. };
  75059. document.addEventListener("keydown", this._onKeyDown);
  75060. // Exiting VR mode double tapping the touch screen
  75061. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75062. if (_this.isInVRMode) {
  75063. _this.exitVR();
  75064. if (_this._fullscreenVRpresenting) {
  75065. _this._scene.getEngine().switchFullscreen(true);
  75066. }
  75067. }
  75068. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75069. // Listen for WebVR display changes
  75070. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75071. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75072. this._onVRRequestPresentStart = function () {
  75073. _this._webVRrequesting = true;
  75074. _this.updateButtonVisibility();
  75075. };
  75076. this._onVRRequestPresentComplete = function (success) {
  75077. _this._webVRrequesting = false;
  75078. _this.updateButtonVisibility();
  75079. };
  75080. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75081. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75082. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75083. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75084. scene.onDisposeObservable.add(function () {
  75085. _this.dispose();
  75086. });
  75087. // Gamepad connection events
  75088. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75089. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75090. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75091. this.updateButtonVisibility();
  75092. //create easing functions
  75093. this._circleEase = new BABYLON.CircleEase();
  75094. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75095. }
  75096. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75097. /** Return this.onEnteringVRObservable
  75098. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75099. */
  75100. get: function () {
  75101. return this.onEnteringVRObservable;
  75102. },
  75103. enumerable: true,
  75104. configurable: true
  75105. });
  75106. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75107. /** Return this.onExitingVRObservable
  75108. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75109. */
  75110. get: function () {
  75111. return this.onExitingVRObservable;
  75112. },
  75113. enumerable: true,
  75114. configurable: true
  75115. });
  75116. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75117. /** Return this.onControllerMeshLoadedObservable
  75118. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75119. */
  75120. get: function () {
  75121. return this.onControllerMeshLoadedObservable;
  75122. },
  75123. enumerable: true,
  75124. configurable: true
  75125. });
  75126. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  75127. get: function () {
  75128. return this._teleportationTarget;
  75129. },
  75130. set: function (value) {
  75131. if (value) {
  75132. value.name = "teleportationTarget";
  75133. this._isDefaultTeleportationTarget = false;
  75134. this._teleportationTarget = value;
  75135. }
  75136. },
  75137. enumerable: true,
  75138. configurable: true
  75139. });
  75140. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  75141. get: function () {
  75142. return this._displayGaze;
  75143. },
  75144. set: function (value) {
  75145. this._displayGaze = value;
  75146. if (!value) {
  75147. this._gazeTracker.isVisible = false;
  75148. }
  75149. },
  75150. enumerable: true,
  75151. configurable: true
  75152. });
  75153. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  75154. get: function () {
  75155. return this._displayLaserPointer;
  75156. },
  75157. set: function (value) {
  75158. this._displayLaserPointer = value;
  75159. if (!value) {
  75160. if (this._rightLaserPointer) {
  75161. this._rightLaserPointer.isVisible = false;
  75162. }
  75163. if (this._leftLaserPointer) {
  75164. this._leftLaserPointer.isVisible = false;
  75165. }
  75166. }
  75167. else {
  75168. if (this._rightLaserPointer) {
  75169. this._rightLaserPointer.isVisible = true;
  75170. }
  75171. else if (this._leftLaserPointer) {
  75172. this._leftLaserPointer.isVisible = true;
  75173. }
  75174. }
  75175. },
  75176. enumerable: true,
  75177. configurable: true
  75178. });
  75179. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  75180. get: function () {
  75181. return this._deviceOrientationCamera;
  75182. },
  75183. enumerable: true,
  75184. configurable: true
  75185. });
  75186. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  75187. // Based on the current WebVR support, returns the current VR camera used
  75188. get: function () {
  75189. if (this._webVRready) {
  75190. return this._webVRCamera;
  75191. }
  75192. else {
  75193. return this._scene.activeCamera;
  75194. }
  75195. },
  75196. enumerable: true,
  75197. configurable: true
  75198. });
  75199. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  75200. get: function () {
  75201. return this._webVRCamera;
  75202. },
  75203. enumerable: true,
  75204. configurable: true
  75205. });
  75206. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  75207. get: function () {
  75208. return this._vrDeviceOrientationCamera;
  75209. },
  75210. enumerable: true,
  75211. configurable: true
  75212. });
  75213. // Raised when one of the controller has loaded successfully its associated default mesh
  75214. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  75215. this._tryEnableInteractionOnController(webVRController);
  75216. try {
  75217. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  75218. }
  75219. catch (err) {
  75220. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  75221. }
  75222. };
  75223. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  75224. /**
  75225. * Gets a value indicating if we are currently in VR mode.
  75226. */
  75227. get: function () {
  75228. return this._webVRpresenting || this._fullscreenVRpresenting;
  75229. },
  75230. enumerable: true,
  75231. configurable: true
  75232. });
  75233. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  75234. var vrDisplay = this._scene.getEngine().getVRDevice();
  75235. if (vrDisplay) {
  75236. var wasPresenting = this._webVRpresenting;
  75237. // A VR display is connected
  75238. this._webVRpresenting = vrDisplay.isPresenting;
  75239. if (wasPresenting && !this._webVRpresenting)
  75240. this.exitVR();
  75241. }
  75242. else {
  75243. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  75244. }
  75245. this.updateButtonVisibility();
  75246. };
  75247. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  75248. this._webVRsupported = eventArgs.vrSupported;
  75249. this._webVRready = !!eventArgs.vrDisplay;
  75250. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  75251. this.updateButtonVisibility();
  75252. };
  75253. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  75254. if (this._canvas && !this._useCustomVRButton) {
  75255. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  75256. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  75257. }
  75258. };
  75259. VRExperienceHelper.prototype.displayVRButton = function () {
  75260. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  75261. document.body.appendChild(this._btnVR);
  75262. this._btnVRDisplayed = true;
  75263. }
  75264. };
  75265. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  75266. if (!this._btnVR || this._useCustomVRButton) {
  75267. return;
  75268. }
  75269. this._btnVR.className = "babylonVRicon";
  75270. if (this.isInVRMode) {
  75271. this._btnVR.className += " vrdisplaypresenting";
  75272. }
  75273. else {
  75274. if (this._webVRready)
  75275. this._btnVR.className += " vrdisplayready";
  75276. if (this._webVRsupported)
  75277. this._btnVR.className += " vrdisplaysupported";
  75278. if (this._webVRrequesting)
  75279. this._btnVR.className += " vrdisplayrequesting";
  75280. }
  75281. };
  75282. /**
  75283. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  75284. * Otherwise, will use the fullscreen API.
  75285. */
  75286. VRExperienceHelper.prototype.enterVR = function () {
  75287. if (this.onEnteringVRObservable) {
  75288. try {
  75289. this.onEnteringVRObservable.notifyObservers(this);
  75290. }
  75291. catch (err) {
  75292. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  75293. }
  75294. }
  75295. if (this._scene.activeCamera) {
  75296. this._position = this._scene.activeCamera.position.clone();
  75297. // make sure that we return to the last active camera
  75298. this._existingCamera = this._scene.activeCamera;
  75299. }
  75300. if (this._webVRrequesting)
  75301. return;
  75302. // If WebVR is supported and a headset is connected
  75303. if (this._webVRready) {
  75304. if (!this._webVRpresenting) {
  75305. this._webVRCamera.position = this._position;
  75306. this._scene.activeCamera = this._webVRCamera;
  75307. }
  75308. }
  75309. else if (this._vrDeviceOrientationCamera) {
  75310. this._vrDeviceOrientationCamera.position = this._position;
  75311. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  75312. this._scene.getEngine().switchFullscreen(true);
  75313. this.updateButtonVisibility();
  75314. }
  75315. if (this._scene.activeCamera && this._canvas) {
  75316. this._scene.activeCamera.attachControl(this._canvas);
  75317. }
  75318. if (this._interactionsEnabled) {
  75319. this._scene.registerBeforeRender(this.beforeRender);
  75320. }
  75321. };
  75322. /**
  75323. * Attempt to exit VR, or fullscreen.
  75324. */
  75325. VRExperienceHelper.prototype.exitVR = function () {
  75326. if (this.onExitingVRObservable) {
  75327. try {
  75328. this.onExitingVRObservable.notifyObservers(this);
  75329. }
  75330. catch (err) {
  75331. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  75332. }
  75333. }
  75334. if (this._webVRpresenting) {
  75335. this._scene.getEngine().disableVR();
  75336. }
  75337. if (this._scene.activeCamera) {
  75338. this._position = this._scene.activeCamera.position.clone();
  75339. }
  75340. if (this._deviceOrientationCamera) {
  75341. this._deviceOrientationCamera.position = this._position;
  75342. this._scene.activeCamera = this._deviceOrientationCamera;
  75343. if (this._canvas) {
  75344. this._scene.activeCamera.attachControl(this._canvas);
  75345. }
  75346. }
  75347. else if (this._existingCamera) {
  75348. this._existingCamera.position = this._position;
  75349. this._scene.activeCamera = this._existingCamera;
  75350. }
  75351. this.updateButtonVisibility();
  75352. if (this._interactionsEnabled) {
  75353. this._scene.unregisterBeforeRender(this.beforeRender);
  75354. }
  75355. };
  75356. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  75357. get: function () {
  75358. return this._position;
  75359. },
  75360. set: function (value) {
  75361. this._position = value;
  75362. if (this._scene.activeCamera) {
  75363. this._scene.activeCamera.position = value;
  75364. }
  75365. },
  75366. enumerable: true,
  75367. configurable: true
  75368. });
  75369. VRExperienceHelper.prototype.enableInteractions = function () {
  75370. var _this = this;
  75371. if (!this._interactionsEnabled) {
  75372. this._interactionsRequested = true;
  75373. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75374. this._enableInteractionOnController(this._webVRCamera.leftController);
  75375. }
  75376. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75377. this._enableInteractionOnController(this._webVRCamera.rightController);
  75378. }
  75379. this._createGazeTracker();
  75380. this.raySelectionPredicate = function (mesh) {
  75381. return mesh.isVisible;
  75382. };
  75383. this.meshSelectionPredicate = function (mesh) {
  75384. return true;
  75385. };
  75386. this._raySelectionPredicate = function (mesh) {
  75387. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  75388. && mesh.name.indexOf("teleportationTarget") === -1
  75389. && mesh.name.indexOf("torusTeleportation") === -1
  75390. && mesh.name.indexOf("laserPointer") === -1)) {
  75391. return _this.raySelectionPredicate(mesh);
  75392. }
  75393. return false;
  75394. };
  75395. this._interactionsEnabled = true;
  75396. }
  75397. };
  75398. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  75399. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  75400. if (this._floorMeshesCollection[i].id === mesh.id) {
  75401. return true;
  75402. }
  75403. }
  75404. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  75405. return true;
  75406. }
  75407. return false;
  75408. };
  75409. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  75410. if (!this._floorMeshesCollection) {
  75411. return;
  75412. }
  75413. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  75414. return;
  75415. }
  75416. this._floorMeshesCollection.push(floorMesh);
  75417. };
  75418. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  75419. if (!this._floorMeshesCollection) {
  75420. return;
  75421. }
  75422. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  75423. if (meshIndex !== -1) {
  75424. this._floorMeshesCollection.splice(meshIndex, 1);
  75425. }
  75426. };
  75427. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  75428. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  75429. if (!this._teleportationInitialized) {
  75430. this._teleportationRequested = true;
  75431. this.enableInteractions();
  75432. if (vrTeleportationOptions.floorMeshName) {
  75433. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  75434. }
  75435. if (vrTeleportationOptions.floorMeshes) {
  75436. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  75437. }
  75438. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75439. this._enableTeleportationOnController(this._webVRCamera.leftController);
  75440. }
  75441. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75442. this._enableTeleportationOnController(this._webVRCamera.rightController);
  75443. }
  75444. // Creates an image processing post process for the vignette not relying
  75445. // on the main scene configuration for image processing to reduce setup and spaces
  75446. // (gamma/linear) conflicts.
  75447. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  75448. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  75449. imageProcessingConfiguration.vignetteEnabled = true;
  75450. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  75451. this._webVRCamera.detachPostProcess(this._postProcessMove);
  75452. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  75453. this._teleportationInitialized = true;
  75454. if (this._isDefaultTeleportationTarget) {
  75455. this._createTeleportationCircles();
  75456. }
  75457. }
  75458. };
  75459. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  75460. var _this = this;
  75461. var controllerMesh = webVRController.mesh;
  75462. if (controllerMesh) {
  75463. var makeNotPick = function (root) {
  75464. root.name += " laserPointer";
  75465. root.getChildMeshes().forEach(function (c) {
  75466. makeNotPick(c);
  75467. });
  75468. };
  75469. makeNotPick(controllerMesh);
  75470. var childMeshes = controllerMesh.getChildMeshes();
  75471. for (var i = 0; i < childMeshes.length; i++) {
  75472. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  75473. controllerMesh = childMeshes[i];
  75474. break;
  75475. }
  75476. }
  75477. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  75478. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  75479. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  75480. laserPointerMaterial.alpha = 0.6;
  75481. laserPointer.material = laserPointerMaterial;
  75482. laserPointer.rotation.x = Math.PI / 2;
  75483. laserPointer.parent = controllerMesh;
  75484. laserPointer.position.z = -0.5;
  75485. laserPointer.isVisible = false;
  75486. if (webVRController.hand === "left") {
  75487. this._leftLaserPointer = laserPointer;
  75488. this._interactionsEnabledOnLeftController = true;
  75489. if (!this._rightLaserPointer) {
  75490. this._leftLaserPointer.isVisible = true;
  75491. }
  75492. }
  75493. else {
  75494. this._rightLaserPointer = laserPointer;
  75495. this._interactionsEnabledOnRightController = true;
  75496. if (!this._leftLaserPointer) {
  75497. this._rightLaserPointer.isVisible = true;
  75498. }
  75499. }
  75500. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  75501. // Enabling / disabling laserPointer
  75502. if (_this._displayLaserPointer && stateObject.value === 1) {
  75503. laserPointer.isVisible = !laserPointer.isVisible;
  75504. // Laser pointer can only be active on left or right, not both at the same time
  75505. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  75506. _this._rightLaserPointer.isVisible = false;
  75507. }
  75508. else if (_this._leftLaserPointer) {
  75509. _this._leftLaserPointer.isVisible = false;
  75510. }
  75511. }
  75512. });
  75513. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  75514. if (!_this._pointerDownOnMeshAsked) {
  75515. if (stateObject.value > _this._padSensibilityUp) {
  75516. _this._selectionPointerDown();
  75517. }
  75518. }
  75519. else if (stateObject.value < _this._padSensibilityDown) {
  75520. _this._selectionPointerUp();
  75521. }
  75522. });
  75523. }
  75524. };
  75525. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  75526. if (webVRController === void 0) { webVRController = null; }
  75527. if (!this._teleportationRequestInitiated) {
  75528. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  75529. if (webVRController) {
  75530. // If laser pointer wasn't enabled yet
  75531. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  75532. this._leftLaserPointer.isVisible = true;
  75533. if (this._rightLaserPointer) {
  75534. this._rightLaserPointer.isVisible = false;
  75535. }
  75536. }
  75537. else if (this._displayLaserPointer && this._rightLaserPointer) {
  75538. this._rightLaserPointer.isVisible = true;
  75539. if (this._leftLaserPointer) {
  75540. this._leftLaserPointer.isVisible = false;
  75541. }
  75542. }
  75543. }
  75544. this._teleportationRequestInitiated = true;
  75545. }
  75546. }
  75547. else {
  75548. // Listening to the proper controller values changes to confirm teleportation
  75549. if (webVRController == null
  75550. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  75551. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  75552. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  75553. if (this._teleportationAllowed) {
  75554. this._teleportationAllowed = false;
  75555. this._teleportCamera();
  75556. }
  75557. this._teleportationRequestInitiated = false;
  75558. }
  75559. }
  75560. }
  75561. };
  75562. VRExperienceHelper.prototype._selectionPointerDown = function () {
  75563. this._pointerDownOnMeshAsked = true;
  75564. if (this._currentMeshSelected && this._currentHit) {
  75565. this._scene.simulatePointerDown(this._currentHit);
  75566. }
  75567. };
  75568. VRExperienceHelper.prototype._selectionPointerUp = function () {
  75569. if (this._currentMeshSelected && this._currentHit) {
  75570. this._scene.simulatePointerUp(this._currentHit);
  75571. }
  75572. this._pointerDownOnMeshAsked = false;
  75573. };
  75574. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  75575. // Only rotate when user is not currently selecting a teleportation location
  75576. if (this._teleportationRequestInitiated) {
  75577. return;
  75578. }
  75579. if (!this._rotationLeftAsked) {
  75580. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  75581. this._rotationLeftAsked = true;
  75582. if (this._rotationAllowed) {
  75583. this._rotateCamera(false);
  75584. }
  75585. }
  75586. }
  75587. else {
  75588. if (stateObject.x > -this._padSensibilityDown) {
  75589. this._rotationLeftAsked = false;
  75590. }
  75591. }
  75592. if (!this._rotationRightAsked) {
  75593. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  75594. this._rotationRightAsked = true;
  75595. if (this._rotationAllowed) {
  75596. this._rotateCamera(true);
  75597. }
  75598. }
  75599. }
  75600. else {
  75601. if (stateObject.x < this._padSensibilityDown) {
  75602. this._rotationRightAsked = false;
  75603. }
  75604. }
  75605. };
  75606. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  75607. // Only teleport backwards when user is not currently selecting a teleportation location
  75608. if (this._teleportationRequestInitiated) {
  75609. return;
  75610. }
  75611. // Teleport backwards
  75612. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  75613. if (!this._teleportationBackRequestInitiated) {
  75614. if (!this.currentVRCamera) {
  75615. return;
  75616. }
  75617. // Get rotation and position of the current camera
  75618. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  75619. var position = this.currentVRCamera.position;
  75620. // If the camera has device position, use that instead
  75621. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  75622. rotation = this.currentVRCamera.deviceRotationQuaternion;
  75623. position = this.currentVRCamera.devicePosition;
  75624. }
  75625. // Get matrix with only the y rotation of the device rotation
  75626. rotation.toEulerAnglesToRef(this._workingVector);
  75627. this._workingVector.z = 0;
  75628. this._workingVector.x = 0;
  75629. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  75630. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  75631. // Rotate backwards ray by device rotation to cast at the ground behind the user
  75632. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  75633. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  75634. var ray = new BABYLON.Ray(position, this._workingVector);
  75635. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  75636. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  75637. this._teleportCamera(hit.pickedPoint);
  75638. }
  75639. this._teleportationBackRequestInitiated = true;
  75640. }
  75641. }
  75642. else {
  75643. this._teleportationBackRequestInitiated = false;
  75644. }
  75645. };
  75646. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  75647. var _this = this;
  75648. var controllerMesh = webVRController.mesh;
  75649. if (controllerMesh) {
  75650. if (webVRController.hand === "left") {
  75651. if (!this._interactionsEnabledOnLeftController) {
  75652. this._enableInteractionOnController(webVRController);
  75653. }
  75654. this._teleportationEnabledOnLeftController = true;
  75655. }
  75656. else {
  75657. if (!this._interactionsEnabledOnRightController) {
  75658. this._enableInteractionOnController(webVRController);
  75659. }
  75660. this._teleportationEnabledOnRightController = true;
  75661. }
  75662. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75663. this._dpadPressed = false;
  75664. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  75665. _this._dpadPressed = stateObject.pressed;
  75666. if (!_this._dpadPressed) {
  75667. _this._rotationLeftAsked = false;
  75668. _this._rotationRightAsked = false;
  75669. _this._teleportationBackRequestInitiated = false;
  75670. }
  75671. });
  75672. }
  75673. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  75674. if (_this.teleportationEnabled) {
  75675. _this._checkTeleportBackwards(stateObject);
  75676. _this._checkTeleportWithRay(stateObject, webVRController);
  75677. }
  75678. _this._checkRotate(stateObject);
  75679. });
  75680. }
  75681. };
  75682. // Gaze support used to point to teleport or to interact with an object
  75683. VRExperienceHelper.prototype._createGazeTracker = function () {
  75684. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  75685. this._gazeTracker.bakeCurrentTransformIntoVertices();
  75686. this._gazeTracker.isPickable = false;
  75687. this._gazeTracker.isVisible = false;
  75688. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  75689. targetMat.specularColor = BABYLON.Color3.Black();
  75690. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  75691. targetMat.backFaceCulling = false;
  75692. this._gazeTracker.material = targetMat;
  75693. };
  75694. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  75695. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  75696. this._teleportationTarget.isPickable = false;
  75697. var length = 512;
  75698. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  75699. dynamicTexture.hasAlpha = true;
  75700. var context = dynamicTexture.getContext();
  75701. var centerX = length / 2;
  75702. var centerY = length / 2;
  75703. var radius = 200;
  75704. context.beginPath();
  75705. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  75706. context.fillStyle = this._teleportationFillColor;
  75707. context.fill();
  75708. context.lineWidth = 10;
  75709. context.strokeStyle = this._teleportationBorderColor;
  75710. context.stroke();
  75711. context.closePath();
  75712. dynamicTexture.update();
  75713. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  75714. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  75715. this._teleportationTarget.material = teleportationCircleMaterial;
  75716. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  75717. torus.isPickable = false;
  75718. torus.parent = this._teleportationTarget;
  75719. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  75720. var keys = [];
  75721. keys.push({
  75722. frame: 0,
  75723. value: 0
  75724. });
  75725. keys.push({
  75726. frame: 30,
  75727. value: 0.4
  75728. });
  75729. keys.push({
  75730. frame: 60,
  75731. value: 0
  75732. });
  75733. animationInnerCircle.setKeys(keys);
  75734. var easingFunction = new BABYLON.SineEase();
  75735. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75736. animationInnerCircle.setEasingFunction(easingFunction);
  75737. torus.animations = [];
  75738. torus.animations.push(animationInnerCircle);
  75739. this._scene.beginAnimation(torus, 0, 60, true);
  75740. this._hideTeleportationTarget();
  75741. };
  75742. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  75743. if (this._teleportationInitialized) {
  75744. this._teleportationTarget.isVisible = true;
  75745. if (this._isDefaultTeleportationTarget) {
  75746. this._teleportationTarget.getChildren()[0].isVisible = true;
  75747. }
  75748. }
  75749. };
  75750. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  75751. if (this._teleportationInitialized) {
  75752. this._teleportationTarget.isVisible = false;
  75753. if (this._isDefaultTeleportationTarget) {
  75754. this._teleportationTarget.getChildren()[0].isVisible = false;
  75755. }
  75756. }
  75757. };
  75758. VRExperienceHelper.prototype._rotateCamera = function (right) {
  75759. var _this = this;
  75760. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  75761. return;
  75762. }
  75763. if (right) {
  75764. this._rotationAngle++;
  75765. }
  75766. else {
  75767. this._rotationAngle--;
  75768. }
  75769. this.currentVRCamera.animations = [];
  75770. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  75771. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75772. var animationRotationKeys = [];
  75773. animationRotationKeys.push({
  75774. frame: 0,
  75775. value: this.currentVRCamera.rotationQuaternion
  75776. });
  75777. animationRotationKeys.push({
  75778. frame: 6,
  75779. value: target
  75780. });
  75781. animationRotation.setKeys(animationRotationKeys);
  75782. animationRotation.setEasingFunction(this._circleEase);
  75783. this.currentVRCamera.animations.push(animationRotation);
  75784. this._postProcessMove.animations = [];
  75785. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75786. var vignetteWeightKeys = [];
  75787. vignetteWeightKeys.push({
  75788. frame: 0,
  75789. value: 0
  75790. });
  75791. vignetteWeightKeys.push({
  75792. frame: 3,
  75793. value: 4
  75794. });
  75795. vignetteWeightKeys.push({
  75796. frame: 6,
  75797. value: 0
  75798. });
  75799. animationPP.setKeys(vignetteWeightKeys);
  75800. animationPP.setEasingFunction(this._circleEase);
  75801. this._postProcessMove.animations.push(animationPP);
  75802. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75803. var vignetteStretchKeys = [];
  75804. vignetteStretchKeys.push({
  75805. frame: 0,
  75806. value: 0
  75807. });
  75808. vignetteStretchKeys.push({
  75809. frame: 3,
  75810. value: 10
  75811. });
  75812. vignetteStretchKeys.push({
  75813. frame: 6,
  75814. value: 0
  75815. });
  75816. animationPP2.setKeys(vignetteStretchKeys);
  75817. animationPP2.setEasingFunction(this._circleEase);
  75818. this._postProcessMove.animations.push(animationPP2);
  75819. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  75820. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  75821. this._webVRCamera.attachPostProcess(this._postProcessMove);
  75822. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  75823. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  75824. });
  75825. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  75826. };
  75827. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  75828. if (hit.pickedPoint) {
  75829. this._teleportationAllowed = true;
  75830. if (this._teleportationRequestInitiated) {
  75831. this._displayTeleportationTarget();
  75832. }
  75833. else {
  75834. this._hideTeleportationTarget();
  75835. }
  75836. this._haloCenter.copyFrom(hit.pickedPoint);
  75837. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  75838. var pickNormal = hit.getNormal(true, false);
  75839. if (pickNormal) {
  75840. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  75841. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  75842. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  75843. }
  75844. this._teleportationTarget.position.y += 0.1;
  75845. }
  75846. };
  75847. VRExperienceHelper.prototype._teleportCamera = function (location) {
  75848. var _this = this;
  75849. if (location === void 0) { location = null; }
  75850. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  75851. return;
  75852. }
  75853. if (!location) {
  75854. location = this._haloCenter;
  75855. }
  75856. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  75857. // offset of the headset from the anchor.
  75858. if (this.webVRCamera.leftCamera) {
  75859. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  75860. this._workingVector.subtractInPlace(this.webVRCamera.position);
  75861. location.subtractToRef(this._workingVector, this._workingVector);
  75862. }
  75863. else {
  75864. this._workingVector.copyFrom(location);
  75865. }
  75866. // Add height to account for user's height offset
  75867. if (this.isInVRMode) {
  75868. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  75869. }
  75870. else {
  75871. this._workingVector.y += this._defaultHeight;
  75872. }
  75873. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  75874. // Create animation from the camera's position to the new location
  75875. this.currentVRCamera.animations = [];
  75876. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75877. var animationCameraTeleportationKeys = [{
  75878. frame: 0,
  75879. value: this.currentVRCamera.position
  75880. },
  75881. {
  75882. frame: 11,
  75883. value: this._workingVector
  75884. }
  75885. ];
  75886. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  75887. animationCameraTeleportation.setEasingFunction(this._circleEase);
  75888. this.currentVRCamera.animations.push(animationCameraTeleportation);
  75889. this._postProcessMove.animations = [];
  75890. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75891. var vignetteWeightKeys = [];
  75892. vignetteWeightKeys.push({
  75893. frame: 0,
  75894. value: 0
  75895. });
  75896. vignetteWeightKeys.push({
  75897. frame: 5,
  75898. value: 8
  75899. });
  75900. vignetteWeightKeys.push({
  75901. frame: 11,
  75902. value: 0
  75903. });
  75904. animationPP.setKeys(vignetteWeightKeys);
  75905. this._postProcessMove.animations.push(animationPP);
  75906. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  75907. var vignetteStretchKeys = [];
  75908. vignetteStretchKeys.push({
  75909. frame: 0,
  75910. value: 0
  75911. });
  75912. vignetteStretchKeys.push({
  75913. frame: 5,
  75914. value: 10
  75915. });
  75916. vignetteStretchKeys.push({
  75917. frame: 11,
  75918. value: 0
  75919. });
  75920. animationPP2.setKeys(vignetteStretchKeys);
  75921. this._postProcessMove.animations.push(animationPP2);
  75922. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  75923. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  75924. this._webVRCamera.attachPostProcess(this._postProcessMove);
  75925. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  75926. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  75927. });
  75928. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  75929. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  75930. });
  75931. };
  75932. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  75933. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  75934. return;
  75935. }
  75936. var ray;
  75937. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  75938. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  75939. }
  75940. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  75941. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  75942. }
  75943. else {
  75944. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  75945. }
  75946. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  75947. // Moving the gazeTracker on the mesh face targetted
  75948. if (hit && hit.pickedPoint) {
  75949. if (this._displayGaze) {
  75950. var multiplier = 1;
  75951. this._gazeTracker.isVisible = true;
  75952. if (this._isActionableMesh) {
  75953. multiplier = 3;
  75954. }
  75955. this._gazeTracker.scaling.x = hit.distance * multiplier;
  75956. this._gazeTracker.scaling.y = hit.distance * multiplier;
  75957. this._gazeTracker.scaling.z = hit.distance * multiplier;
  75958. var pickNormal = hit.getNormal();
  75959. // To avoid z-fighting
  75960. var deltaFighting = 0.002;
  75961. if (pickNormal) {
  75962. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  75963. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  75964. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  75965. }
  75966. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  75967. if (this._gazeTracker.position.x < 0) {
  75968. this._gazeTracker.position.x += deltaFighting;
  75969. }
  75970. else {
  75971. this._gazeTracker.position.x -= deltaFighting;
  75972. }
  75973. if (this._gazeTracker.position.y < 0) {
  75974. this._gazeTracker.position.y += deltaFighting;
  75975. }
  75976. else {
  75977. this._gazeTracker.position.y -= deltaFighting;
  75978. }
  75979. if (this._gazeTracker.position.z < 0) {
  75980. this._gazeTracker.position.z += deltaFighting;
  75981. }
  75982. else {
  75983. this._gazeTracker.position.z -= deltaFighting;
  75984. }
  75985. }
  75986. // Changing the size of the laser pointer based on the distance from the targetted point
  75987. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  75988. this._rightLaserPointer.scaling.y = hit.distance;
  75989. this._rightLaserPointer.position.z = -hit.distance / 2;
  75990. }
  75991. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  75992. this._leftLaserPointer.scaling.y = hit.distance;
  75993. this._leftLaserPointer.position.z = -hit.distance / 2;
  75994. }
  75995. }
  75996. else {
  75997. this._gazeTracker.isVisible = false;
  75998. }
  75999. if (hit && hit.pickedMesh) {
  76000. this._currentHit = hit;
  76001. if (this._pointerDownOnMeshAsked) {
  76002. this._scene.simulatePointerMove(this._currentHit);
  76003. }
  76004. // The object selected is the floor, we're in a teleportation scenario
  76005. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76006. // Moving the teleportation area to this targetted point
  76007. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76008. if (this._currentMeshSelected &&
  76009. !this._isTeleportationFloor(this._currentMeshSelected)) {
  76010. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76011. }
  76012. this._currentMeshSelected = null;
  76013. this._moveTeleportationSelectorTo(hit);
  76014. return;
  76015. }
  76016. // If not, we're in a selection scenario
  76017. this._hideTeleportationTarget();
  76018. this._teleportationAllowed = false;
  76019. if (hit.pickedMesh !== this._currentMeshSelected) {
  76020. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76021. this.onNewMeshPicked.notifyObservers(hit);
  76022. this._currentMeshSelected = hit.pickedMesh;
  76023. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76024. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76025. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76026. this._isActionableMesh = true;
  76027. }
  76028. else {
  76029. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76030. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76031. this._isActionableMesh = false;
  76032. }
  76033. try {
  76034. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76035. }
  76036. catch (err) {
  76037. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76038. }
  76039. }
  76040. else {
  76041. if (this._currentMeshSelected) {
  76042. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76043. }
  76044. this._currentMeshSelected = null;
  76045. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76046. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76047. }
  76048. }
  76049. }
  76050. else {
  76051. this._currentHit = null;
  76052. this._currentMeshSelected = null;
  76053. this._teleportationAllowed = false;
  76054. this._hideTeleportationTarget();
  76055. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76056. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76057. }
  76058. };
  76059. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76060. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76061. this._leftLaserPointer.material.emissiveColor = color;
  76062. }
  76063. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76064. this._rightLaserPointer.material.emissiveColor = color;
  76065. }
  76066. };
  76067. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  76068. if (this._gazeTracker.material) {
  76069. this._gazeTracker.material.emissiveColor = color;
  76070. }
  76071. };
  76072. VRExperienceHelper.prototype.dispose = function () {
  76073. if (this.isInVRMode) {
  76074. this.exitVR();
  76075. }
  76076. if (this._passProcessMove) {
  76077. this._passProcessMove.dispose();
  76078. }
  76079. if (this._postProcessMove) {
  76080. this._postProcessMove.dispose();
  76081. }
  76082. if (this._webVRCamera) {
  76083. this._webVRCamera.dispose();
  76084. }
  76085. if (this._vrDeviceOrientationCamera) {
  76086. this._vrDeviceOrientationCamera.dispose();
  76087. }
  76088. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  76089. document.body.removeChild(this._btnVR);
  76090. }
  76091. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  76092. this._deviceOrientationCamera.dispose();
  76093. }
  76094. if (this._gazeTracker) {
  76095. this._gazeTracker.dispose();
  76096. }
  76097. if (this._teleportationTarget) {
  76098. this._teleportationTarget.dispose();
  76099. }
  76100. this._floorMeshesCollection = [];
  76101. document.removeEventListener("keydown", this._onKeyDown);
  76102. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76103. window.removeEventListener("resize", this._onResize);
  76104. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  76105. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  76106. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  76107. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  76108. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  76109. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  76110. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  76111. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76112. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  76113. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  76114. this._scene.unregisterBeforeRender(this.beforeRender);
  76115. };
  76116. VRExperienceHelper.prototype.getClassName = function () {
  76117. return "VRExperienceHelper";
  76118. };
  76119. return VRExperienceHelper;
  76120. }());
  76121. BABYLON.VRExperienceHelper = VRExperienceHelper;
  76122. })(BABYLON || (BABYLON = {}));
  76123. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  76124. // Mainly based on these 2 articles :
  76125. // 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
  76126. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  76127. var BABYLON;
  76128. (function (BABYLON) {
  76129. var JoystickAxis;
  76130. (function (JoystickAxis) {
  76131. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  76132. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  76133. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  76134. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  76135. var VirtualJoystick = /** @class */ (function () {
  76136. function VirtualJoystick(leftJoystick) {
  76137. var _this = this;
  76138. if (leftJoystick) {
  76139. this._leftJoystick = true;
  76140. }
  76141. else {
  76142. this._leftJoystick = false;
  76143. }
  76144. VirtualJoystick._globalJoystickIndex++;
  76145. // By default left & right arrow keys are moving the X
  76146. // and up & down keys are moving the Y
  76147. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76148. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76149. this.reverseLeftRight = false;
  76150. this.reverseUpDown = false;
  76151. // collections of pointers
  76152. this._touches = new BABYLON.StringDictionary();
  76153. this.deltaPosition = BABYLON.Vector3.Zero();
  76154. this._joystickSensibility = 25;
  76155. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76156. this._onResize = function (evt) {
  76157. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76158. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76159. if (VirtualJoystick.vjCanvas) {
  76160. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  76161. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  76162. }
  76163. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  76164. };
  76165. // injecting a canvas element on top of the canvas 3D game
  76166. if (!VirtualJoystick.vjCanvas) {
  76167. window.addEventListener("resize", this._onResize, false);
  76168. VirtualJoystick.vjCanvas = document.createElement("canvas");
  76169. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76170. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76171. VirtualJoystick.vjCanvas.width = window.innerWidth;
  76172. VirtualJoystick.vjCanvas.height = window.innerHeight;
  76173. VirtualJoystick.vjCanvas.style.width = "100%";
  76174. VirtualJoystick.vjCanvas.style.height = "100%";
  76175. VirtualJoystick.vjCanvas.style.position = "absolute";
  76176. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  76177. VirtualJoystick.vjCanvas.style.top = "0px";
  76178. VirtualJoystick.vjCanvas.style.left = "0px";
  76179. VirtualJoystick.vjCanvas.style.zIndex = "5";
  76180. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  76181. // Support for jQuery PEP polyfill
  76182. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  76183. var context = VirtualJoystick.vjCanvas.getContext('2d');
  76184. if (!context) {
  76185. throw new Error("Unable to create canvas for virtual joystick");
  76186. }
  76187. VirtualJoystick.vjCanvasContext = context;
  76188. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  76189. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76190. document.body.appendChild(VirtualJoystick.vjCanvas);
  76191. }
  76192. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  76193. this.pressed = false;
  76194. // default joystick color
  76195. this._joystickColor = "cyan";
  76196. this._joystickPointerID = -1;
  76197. // current joystick position
  76198. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  76199. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  76200. // origin joystick position
  76201. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  76202. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  76203. this._onPointerDownHandlerRef = function (evt) {
  76204. _this._onPointerDown(evt);
  76205. };
  76206. this._onPointerMoveHandlerRef = function (evt) {
  76207. _this._onPointerMove(evt);
  76208. };
  76209. this._onPointerUpHandlerRef = function (evt) {
  76210. _this._onPointerUp(evt);
  76211. };
  76212. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  76213. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  76214. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  76215. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  76216. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  76217. evt.preventDefault(); // Disables system menu
  76218. }, false);
  76219. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76220. }
  76221. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  76222. this._joystickSensibility = newJoystickSensibility;
  76223. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76224. };
  76225. VirtualJoystick.prototype._onPointerDown = function (e) {
  76226. var positionOnScreenCondition;
  76227. e.preventDefault();
  76228. if (this._leftJoystick === true) {
  76229. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  76230. }
  76231. else {
  76232. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  76233. }
  76234. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  76235. // First contact will be dedicated to the virtual joystick
  76236. this._joystickPointerID = e.pointerId;
  76237. this._joystickPointerStartPos.x = e.clientX;
  76238. this._joystickPointerStartPos.y = e.clientY;
  76239. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  76240. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  76241. this._deltaJoystickVector.x = 0;
  76242. this._deltaJoystickVector.y = 0;
  76243. this.pressed = true;
  76244. this._touches.add(e.pointerId.toString(), e);
  76245. }
  76246. else {
  76247. // You can only trigger the action buttons with a joystick declared
  76248. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  76249. this._action();
  76250. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  76251. }
  76252. }
  76253. };
  76254. VirtualJoystick.prototype._onPointerMove = function (e) {
  76255. // If the current pointer is the one associated to the joystick (first touch contact)
  76256. if (this._joystickPointerID == e.pointerId) {
  76257. this._joystickPointerPos.x = e.clientX;
  76258. this._joystickPointerPos.y = e.clientY;
  76259. this._deltaJoystickVector = this._joystickPointerPos.clone();
  76260. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  76261. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  76262. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  76263. switch (this._axisTargetedByLeftAndRight) {
  76264. case JoystickAxis.X:
  76265. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  76266. break;
  76267. case JoystickAxis.Y:
  76268. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  76269. break;
  76270. case JoystickAxis.Z:
  76271. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  76272. break;
  76273. }
  76274. var directionUpDown = this.reverseUpDown ? 1 : -1;
  76275. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  76276. switch (this._axisTargetedByUpAndDown) {
  76277. case JoystickAxis.X:
  76278. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  76279. break;
  76280. case JoystickAxis.Y:
  76281. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  76282. break;
  76283. case JoystickAxis.Z:
  76284. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  76285. break;
  76286. }
  76287. }
  76288. else {
  76289. var data = this._touches.get(e.pointerId.toString());
  76290. if (data) {
  76291. data.x = e.clientX;
  76292. data.y = e.clientY;
  76293. }
  76294. }
  76295. };
  76296. VirtualJoystick.prototype._onPointerUp = function (e) {
  76297. if (this._joystickPointerID == e.pointerId) {
  76298. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  76299. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  76300. this._joystickPointerID = -1;
  76301. this.pressed = false;
  76302. }
  76303. else {
  76304. var touch = this._touches.get(e.pointerId.toString());
  76305. if (touch) {
  76306. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76307. }
  76308. }
  76309. this._deltaJoystickVector.x = 0;
  76310. this._deltaJoystickVector.y = 0;
  76311. this._touches.remove(e.pointerId.toString());
  76312. };
  76313. /**
  76314. * Change the color of the virtual joystick
  76315. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  76316. */
  76317. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  76318. this._joystickColor = newColor;
  76319. };
  76320. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  76321. this._action = action;
  76322. };
  76323. // Define which axis you'd like to control for left & right
  76324. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  76325. switch (axis) {
  76326. case JoystickAxis.X:
  76327. case JoystickAxis.Y:
  76328. case JoystickAxis.Z:
  76329. this._axisTargetedByLeftAndRight = axis;
  76330. break;
  76331. default:
  76332. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76333. break;
  76334. }
  76335. };
  76336. // Define which axis you'd like to control for up & down
  76337. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  76338. switch (axis) {
  76339. case JoystickAxis.X:
  76340. case JoystickAxis.Y:
  76341. case JoystickAxis.Z:
  76342. this._axisTargetedByUpAndDown = axis;
  76343. break;
  76344. default:
  76345. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76346. break;
  76347. }
  76348. };
  76349. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  76350. var _this = this;
  76351. if (this.pressed) {
  76352. this._touches.forEach(function (key, touch) {
  76353. if (touch.pointerId === _this._joystickPointerID) {
  76354. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  76355. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  76356. VirtualJoystick.vjCanvasContext.beginPath();
  76357. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76358. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76359. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  76360. VirtualJoystick.vjCanvasContext.stroke();
  76361. VirtualJoystick.vjCanvasContext.closePath();
  76362. VirtualJoystick.vjCanvasContext.beginPath();
  76363. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76364. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76365. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  76366. VirtualJoystick.vjCanvasContext.stroke();
  76367. VirtualJoystick.vjCanvasContext.closePath();
  76368. VirtualJoystick.vjCanvasContext.beginPath();
  76369. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76370. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  76371. VirtualJoystick.vjCanvasContext.stroke();
  76372. VirtualJoystick.vjCanvasContext.closePath();
  76373. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  76374. }
  76375. else {
  76376. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76377. VirtualJoystick.vjCanvasContext.beginPath();
  76378. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  76379. VirtualJoystick.vjCanvasContext.beginPath();
  76380. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  76381. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76382. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  76383. VirtualJoystick.vjCanvasContext.stroke();
  76384. VirtualJoystick.vjCanvasContext.closePath();
  76385. touch.prevX = touch.x;
  76386. touch.prevY = touch.y;
  76387. }
  76388. ;
  76389. });
  76390. }
  76391. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76392. };
  76393. VirtualJoystick.prototype.releaseCanvas = function () {
  76394. if (VirtualJoystick.vjCanvas) {
  76395. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  76396. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  76397. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  76398. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  76399. window.removeEventListener("resize", this._onResize);
  76400. document.body.removeChild(VirtualJoystick.vjCanvas);
  76401. VirtualJoystick.vjCanvas = null;
  76402. }
  76403. };
  76404. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  76405. VirtualJoystick._globalJoystickIndex = 0;
  76406. return VirtualJoystick;
  76407. }());
  76408. BABYLON.VirtualJoystick = VirtualJoystick;
  76409. })(BABYLON || (BABYLON = {}));
  76410. //# sourceMappingURL=babylon.virtualJoystick.js.map
  76411. var BABYLON;
  76412. (function (BABYLON) {
  76413. // We're mainly based on the logic defined into the FreeCamera code
  76414. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  76415. __extends(VirtualJoysticksCamera, _super);
  76416. function VirtualJoysticksCamera(name, position, scene) {
  76417. var _this = _super.call(this, name, position, scene) || this;
  76418. _this.inputs.addVirtualJoystick();
  76419. return _this;
  76420. }
  76421. VirtualJoysticksCamera.prototype.getClassName = function () {
  76422. return "VirtualJoysticksCamera";
  76423. };
  76424. return VirtualJoysticksCamera;
  76425. }(BABYLON.FreeCamera));
  76426. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  76427. })(BABYLON || (BABYLON = {}));
  76428. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  76429. var BABYLON;
  76430. (function (BABYLON) {
  76431. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  76432. function FreeCameraVirtualJoystickInput() {
  76433. }
  76434. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  76435. return this._leftjoystick;
  76436. };
  76437. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  76438. return this._rightjoystick;
  76439. };
  76440. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  76441. if (this._leftjoystick) {
  76442. var camera = this.camera;
  76443. var speed = camera._computeLocalCameraSpeed() * 50;
  76444. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  76445. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  76446. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  76447. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  76448. if (!this._leftjoystick.pressed) {
  76449. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  76450. }
  76451. if (!this._rightjoystick.pressed) {
  76452. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  76453. }
  76454. }
  76455. };
  76456. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  76457. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  76458. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  76459. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  76460. this._leftjoystick.setJoystickSensibility(0.15);
  76461. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  76462. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  76463. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  76464. this._rightjoystick.reverseUpDown = true;
  76465. this._rightjoystick.setJoystickSensibility(0.05);
  76466. this._rightjoystick.setJoystickColor("yellow");
  76467. };
  76468. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  76469. this._leftjoystick.releaseCanvas();
  76470. this._rightjoystick.releaseCanvas();
  76471. };
  76472. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  76473. return "FreeCameraVirtualJoystickInput";
  76474. };
  76475. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  76476. return "virtualJoystick";
  76477. };
  76478. return FreeCameraVirtualJoystickInput;
  76479. }());
  76480. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  76481. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  76482. })(BABYLON || (BABYLON = {}));
  76483. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  76484. var BABYLON;
  76485. (function (BABYLON) {
  76486. var SimplificationSettings = /** @class */ (function () {
  76487. function SimplificationSettings(quality, distance, optimizeMesh) {
  76488. this.quality = quality;
  76489. this.distance = distance;
  76490. this.optimizeMesh = optimizeMesh;
  76491. }
  76492. return SimplificationSettings;
  76493. }());
  76494. BABYLON.SimplificationSettings = SimplificationSettings;
  76495. var SimplificationQueue = /** @class */ (function () {
  76496. function SimplificationQueue() {
  76497. this.running = false;
  76498. this._simplificationArray = [];
  76499. }
  76500. SimplificationQueue.prototype.addTask = function (task) {
  76501. this._simplificationArray.push(task);
  76502. };
  76503. SimplificationQueue.prototype.executeNext = function () {
  76504. var task = this._simplificationArray.pop();
  76505. if (task) {
  76506. this.running = true;
  76507. this.runSimplification(task);
  76508. }
  76509. else {
  76510. this.running = false;
  76511. }
  76512. };
  76513. SimplificationQueue.prototype.runSimplification = function (task) {
  76514. var _this = this;
  76515. if (task.parallelProcessing) {
  76516. //parallel simplifier
  76517. task.settings.forEach(function (setting) {
  76518. var simplifier = _this.getSimplifier(task);
  76519. simplifier.simplify(setting, function (newMesh) {
  76520. task.mesh.addLODLevel(setting.distance, newMesh);
  76521. newMesh.isVisible = true;
  76522. //check if it is the last
  76523. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  76524. //all done, run the success callback.
  76525. task.successCallback();
  76526. }
  76527. _this.executeNext();
  76528. });
  76529. });
  76530. }
  76531. else {
  76532. //single simplifier.
  76533. var simplifier = this.getSimplifier(task);
  76534. var runDecimation = function (setting, callback) {
  76535. simplifier.simplify(setting, function (newMesh) {
  76536. task.mesh.addLODLevel(setting.distance, newMesh);
  76537. newMesh.isVisible = true;
  76538. //run the next quality level
  76539. callback();
  76540. });
  76541. };
  76542. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  76543. runDecimation(task.settings[loop.index], function () {
  76544. loop.executeNext();
  76545. });
  76546. }, function () {
  76547. //execution ended, run the success callback.
  76548. if (task.successCallback) {
  76549. task.successCallback();
  76550. }
  76551. _this.executeNext();
  76552. });
  76553. }
  76554. };
  76555. SimplificationQueue.prototype.getSimplifier = function (task) {
  76556. switch (task.simplificationType) {
  76557. case SimplificationType.QUADRATIC:
  76558. default:
  76559. return new QuadraticErrorSimplification(task.mesh);
  76560. }
  76561. };
  76562. return SimplificationQueue;
  76563. }());
  76564. BABYLON.SimplificationQueue = SimplificationQueue;
  76565. /**
  76566. * The implemented types of simplification.
  76567. * At the moment only Quadratic Error Decimation is implemented.
  76568. */
  76569. var SimplificationType;
  76570. (function (SimplificationType) {
  76571. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  76572. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  76573. var DecimationTriangle = /** @class */ (function () {
  76574. function DecimationTriangle(vertices) {
  76575. this.vertices = vertices;
  76576. this.error = new Array(4);
  76577. this.deleted = false;
  76578. this.isDirty = false;
  76579. this.deletePending = false;
  76580. this.borderFactor = 0;
  76581. }
  76582. return DecimationTriangle;
  76583. }());
  76584. BABYLON.DecimationTriangle = DecimationTriangle;
  76585. var DecimationVertex = /** @class */ (function () {
  76586. function DecimationVertex(position, id) {
  76587. this.position = position;
  76588. this.id = id;
  76589. this.isBorder = true;
  76590. this.q = new QuadraticMatrix();
  76591. this.triangleCount = 0;
  76592. this.triangleStart = 0;
  76593. this.originalOffsets = [];
  76594. }
  76595. DecimationVertex.prototype.updatePosition = function (newPosition) {
  76596. this.position.copyFrom(newPosition);
  76597. };
  76598. return DecimationVertex;
  76599. }());
  76600. BABYLON.DecimationVertex = DecimationVertex;
  76601. var QuadraticMatrix = /** @class */ (function () {
  76602. function QuadraticMatrix(data) {
  76603. this.data = new Array(10);
  76604. for (var i = 0; i < 10; ++i) {
  76605. if (data && data[i]) {
  76606. this.data[i] = data[i];
  76607. }
  76608. else {
  76609. this.data[i] = 0;
  76610. }
  76611. }
  76612. }
  76613. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  76614. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  76615. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  76616. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  76617. return det;
  76618. };
  76619. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  76620. for (var i = 0; i < 10; ++i) {
  76621. this.data[i] += matrix.data[i];
  76622. }
  76623. };
  76624. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  76625. for (var i = 0; i < 10; ++i) {
  76626. this.data[i] += data[i];
  76627. }
  76628. };
  76629. QuadraticMatrix.prototype.add = function (matrix) {
  76630. var m = new QuadraticMatrix();
  76631. for (var i = 0; i < 10; ++i) {
  76632. m.data[i] = this.data[i] + matrix.data[i];
  76633. }
  76634. return m;
  76635. };
  76636. QuadraticMatrix.FromData = function (a, b, c, d) {
  76637. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  76638. };
  76639. //returning an array to avoid garbage collection
  76640. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  76641. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  76642. };
  76643. return QuadraticMatrix;
  76644. }());
  76645. BABYLON.QuadraticMatrix = QuadraticMatrix;
  76646. var Reference = /** @class */ (function () {
  76647. function Reference(vertexId, triangleId) {
  76648. this.vertexId = vertexId;
  76649. this.triangleId = triangleId;
  76650. }
  76651. return Reference;
  76652. }());
  76653. BABYLON.Reference = Reference;
  76654. /**
  76655. * An implementation of the Quadratic Error simplification algorithm.
  76656. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  76657. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  76658. * @author RaananW
  76659. */
  76660. var QuadraticErrorSimplification = /** @class */ (function () {
  76661. function QuadraticErrorSimplification(_mesh) {
  76662. this._mesh = _mesh;
  76663. this.syncIterations = 5000;
  76664. this.aggressiveness = 7;
  76665. this.decimationIterations = 100;
  76666. this.boundingBoxEpsilon = BABYLON.Epsilon;
  76667. }
  76668. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  76669. var _this = this;
  76670. this.initDecimatedMesh();
  76671. //iterating through the submeshes array, one after the other.
  76672. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  76673. _this.initWithMesh(loop.index, function () {
  76674. _this.runDecimation(settings, loop.index, function () {
  76675. loop.executeNext();
  76676. });
  76677. }, settings.optimizeMesh);
  76678. }, function () {
  76679. setTimeout(function () {
  76680. successCallback(_this._reconstructedMesh);
  76681. }, 0);
  76682. });
  76683. };
  76684. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  76685. var _this = this;
  76686. var targetCount = ~~(this.triangles.length * settings.quality);
  76687. var deletedTriangles = 0;
  76688. var triangleCount = this.triangles.length;
  76689. var iterationFunction = function (iteration, callback) {
  76690. setTimeout(function () {
  76691. if (iteration % 5 === 0) {
  76692. _this.updateMesh(iteration === 0);
  76693. }
  76694. for (var i = 0; i < _this.triangles.length; ++i) {
  76695. _this.triangles[i].isDirty = false;
  76696. }
  76697. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  76698. var trianglesIterator = function (i) {
  76699. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  76700. var t = _this.triangles[tIdx];
  76701. if (!t)
  76702. return;
  76703. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  76704. return;
  76705. }
  76706. for (var j = 0; j < 3; ++j) {
  76707. if (t.error[j] < threshold) {
  76708. var deleted0 = [];
  76709. var deleted1 = [];
  76710. var v0 = t.vertices[j];
  76711. var v1 = t.vertices[(j + 1) % 3];
  76712. if (v0.isBorder || v1.isBorder)
  76713. continue;
  76714. var p = BABYLON.Vector3.Zero();
  76715. var n = BABYLON.Vector3.Zero();
  76716. var uv = BABYLON.Vector2.Zero();
  76717. var color = new BABYLON.Color4(0, 0, 0, 1);
  76718. _this.calculateError(v0, v1, p, n, uv, color);
  76719. var delTr = new Array();
  76720. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  76721. continue;
  76722. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  76723. continue;
  76724. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  76725. continue;
  76726. var uniqueArray = new Array();
  76727. delTr.forEach(function (deletedT) {
  76728. if (uniqueArray.indexOf(deletedT) === -1) {
  76729. deletedT.deletePending = true;
  76730. uniqueArray.push(deletedT);
  76731. }
  76732. });
  76733. if (uniqueArray.length % 2 !== 0) {
  76734. continue;
  76735. }
  76736. v0.q = v1.q.add(v0.q);
  76737. v0.updatePosition(p);
  76738. var tStart = _this.references.length;
  76739. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  76740. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  76741. var tCount = _this.references.length - tStart;
  76742. if (tCount <= v0.triangleCount) {
  76743. if (tCount) {
  76744. for (var c = 0; c < tCount; c++) {
  76745. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  76746. }
  76747. }
  76748. }
  76749. else {
  76750. v0.triangleStart = tStart;
  76751. }
  76752. v0.triangleCount = tCount;
  76753. break;
  76754. }
  76755. }
  76756. };
  76757. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  76758. }, 0);
  76759. };
  76760. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  76761. if (triangleCount - deletedTriangles <= targetCount)
  76762. loop.breakLoop();
  76763. else {
  76764. iterationFunction(loop.index, function () {
  76765. loop.executeNext();
  76766. });
  76767. }
  76768. }, function () {
  76769. setTimeout(function () {
  76770. //reconstruct this part of the mesh
  76771. _this.reconstructMesh(submeshIndex);
  76772. successCallback();
  76773. }, 0);
  76774. });
  76775. };
  76776. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  76777. var _this = this;
  76778. this.vertices = [];
  76779. this.triangles = [];
  76780. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76781. var indices = this._mesh.getIndices();
  76782. var submesh = this._mesh.subMeshes[submeshIndex];
  76783. var findInVertices = function (positionToSearch) {
  76784. if (optimizeMesh) {
  76785. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  76786. if (_this.vertices[ii].position.equals(positionToSearch)) {
  76787. return _this.vertices[ii];
  76788. }
  76789. }
  76790. }
  76791. return null;
  76792. };
  76793. var vertexReferences = [];
  76794. var vertexInit = function (i) {
  76795. if (!positionData) {
  76796. return;
  76797. }
  76798. var offset = i + submesh.verticesStart;
  76799. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  76800. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  76801. vertex.originalOffsets.push(offset);
  76802. if (vertex.id === _this.vertices.length) {
  76803. _this.vertices.push(vertex);
  76804. }
  76805. vertexReferences.push(vertex.id);
  76806. };
  76807. //var totalVertices = mesh.getTotalVertices();
  76808. var totalVertices = submesh.verticesCount;
  76809. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  76810. var indicesInit = function (i) {
  76811. if (!indices) {
  76812. return;
  76813. }
  76814. var offset = (submesh.indexStart / 3) + i;
  76815. var pos = (offset * 3);
  76816. var i0 = indices[pos + 0];
  76817. var i1 = indices[pos + 1];
  76818. var i2 = indices[pos + 2];
  76819. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  76820. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  76821. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  76822. var triangle = new DecimationTriangle([v0, v1, v2]);
  76823. triangle.originalOffset = pos;
  76824. _this.triangles.push(triangle);
  76825. };
  76826. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  76827. _this.init(callback);
  76828. });
  76829. });
  76830. };
  76831. QuadraticErrorSimplification.prototype.init = function (callback) {
  76832. var _this = this;
  76833. var triangleInit1 = function (i) {
  76834. var t = _this.triangles[i];
  76835. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  76836. for (var j = 0; j < 3; j++) {
  76837. 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))));
  76838. }
  76839. };
  76840. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  76841. var triangleInit2 = function (i) {
  76842. var t = _this.triangles[i];
  76843. for (var j = 0; j < 3; ++j) {
  76844. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  76845. }
  76846. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  76847. };
  76848. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  76849. callback();
  76850. });
  76851. });
  76852. };
  76853. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  76854. var newTriangles = [];
  76855. var i;
  76856. for (i = 0; i < this.vertices.length; ++i) {
  76857. this.vertices[i].triangleCount = 0;
  76858. }
  76859. var t;
  76860. var j;
  76861. for (i = 0; i < this.triangles.length; ++i) {
  76862. if (!this.triangles[i].deleted) {
  76863. t = this.triangles[i];
  76864. for (j = 0; j < 3; ++j) {
  76865. t.vertices[j].triangleCount = 1;
  76866. }
  76867. newTriangles.push(t);
  76868. }
  76869. }
  76870. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  76871. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  76872. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  76873. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  76874. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  76875. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76876. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  76877. var vertexCount = 0;
  76878. for (i = 0; i < this.vertices.length; ++i) {
  76879. var vertex = this.vertices[i];
  76880. vertex.id = vertexCount;
  76881. if (vertex.triangleCount) {
  76882. vertex.originalOffsets.forEach(function (originalOffset) {
  76883. if (!normalData) {
  76884. return;
  76885. }
  76886. newPositionData.push(vertex.position.x);
  76887. newPositionData.push(vertex.position.y);
  76888. newPositionData.push(vertex.position.z);
  76889. newNormalData.push(normalData[originalOffset * 3]);
  76890. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  76891. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  76892. if (uvs && uvs.length) {
  76893. newUVsData.push(uvs[(originalOffset * 2)]);
  76894. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  76895. }
  76896. else if (colorsData && colorsData.length) {
  76897. newColorsData.push(colorsData[(originalOffset * 4)]);
  76898. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  76899. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  76900. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  76901. }
  76902. ++vertexCount;
  76903. });
  76904. }
  76905. }
  76906. var startingIndex = this._reconstructedMesh.getTotalIndices();
  76907. var startingVertex = this._reconstructedMesh.getTotalVertices();
  76908. var submeshesArray = this._reconstructedMesh.subMeshes;
  76909. this._reconstructedMesh.subMeshes = [];
  76910. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  76911. var originalIndices = this._mesh.getIndices();
  76912. for (i = 0; i < newTriangles.length; ++i) {
  76913. t = newTriangles[i]; //now get the new referencing point for each vertex
  76914. [0, 1, 2].forEach(function (idx) {
  76915. var id = originalIndices[t.originalOffset + idx];
  76916. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  76917. if (offset < 0)
  76918. offset = 0;
  76919. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  76920. });
  76921. }
  76922. //overwriting the old vertex buffers and indices.
  76923. this._reconstructedMesh.setIndices(newIndicesArray);
  76924. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  76925. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  76926. if (newUVsData.length > 0)
  76927. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  76928. if (newColorsData.length > 0)
  76929. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  76930. //create submesh
  76931. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  76932. if (submeshIndex > 0) {
  76933. this._reconstructedMesh.subMeshes = [];
  76934. submeshesArray.forEach(function (submesh) {
  76935. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  76936. });
  76937. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  76938. }
  76939. };
  76940. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  76941. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  76942. this._reconstructedMesh.material = this._mesh.material;
  76943. this._reconstructedMesh.parent = this._mesh.parent;
  76944. this._reconstructedMesh.isVisible = false;
  76945. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  76946. };
  76947. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  76948. for (var i = 0; i < vertex1.triangleCount; ++i) {
  76949. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  76950. if (t.deleted)
  76951. continue;
  76952. var s = this.references[vertex1.triangleStart + i].vertexId;
  76953. var v1 = t.vertices[(s + 1) % 3];
  76954. var v2 = t.vertices[(s + 2) % 3];
  76955. if ((v1 === vertex2 || v2 === vertex2)) {
  76956. deletedArray[i] = true;
  76957. delTr.push(t);
  76958. continue;
  76959. }
  76960. var d1 = v1.position.subtract(point);
  76961. d1 = d1.normalize();
  76962. var d2 = v2.position.subtract(point);
  76963. d2 = d2.normalize();
  76964. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  76965. return true;
  76966. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  76967. deletedArray[i] = false;
  76968. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  76969. return true;
  76970. }
  76971. return false;
  76972. };
  76973. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  76974. var newDeleted = deletedTriangles;
  76975. for (var i = 0; i < vertex.triangleCount; ++i) {
  76976. var ref = this.references[vertex.triangleStart + i];
  76977. var t = this.triangles[ref.triangleId];
  76978. if (t.deleted)
  76979. continue;
  76980. if (deletedArray[i] && t.deletePending) {
  76981. t.deleted = true;
  76982. newDeleted++;
  76983. continue;
  76984. }
  76985. t.vertices[ref.vertexId] = origVertex;
  76986. t.isDirty = true;
  76987. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  76988. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  76989. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  76990. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  76991. this.references.push(ref);
  76992. }
  76993. return newDeleted;
  76994. };
  76995. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  76996. for (var i = 0; i < this.vertices.length; ++i) {
  76997. var vCount = [];
  76998. var vId = [];
  76999. var v = this.vertices[i];
  77000. var j;
  77001. for (j = 0; j < v.triangleCount; ++j) {
  77002. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77003. for (var ii = 0; ii < 3; ii++) {
  77004. var ofs = 0;
  77005. var vv = triangle.vertices[ii];
  77006. while (ofs < vCount.length) {
  77007. if (vId[ofs] === vv.id)
  77008. break;
  77009. ++ofs;
  77010. }
  77011. if (ofs === vCount.length) {
  77012. vCount.push(1);
  77013. vId.push(vv.id);
  77014. }
  77015. else {
  77016. vCount[ofs]++;
  77017. }
  77018. }
  77019. }
  77020. for (j = 0; j < vCount.length; ++j) {
  77021. if (vCount[j] === 1) {
  77022. this.vertices[vId[j]].isBorder = true;
  77023. }
  77024. else {
  77025. this.vertices[vId[j]].isBorder = false;
  77026. }
  77027. }
  77028. }
  77029. };
  77030. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77031. if (identifyBorders === void 0) { identifyBorders = false; }
  77032. var i;
  77033. if (!identifyBorders) {
  77034. var newTrianglesVector = [];
  77035. for (i = 0; i < this.triangles.length; ++i) {
  77036. if (!this.triangles[i].deleted) {
  77037. newTrianglesVector.push(this.triangles[i]);
  77038. }
  77039. }
  77040. this.triangles = newTrianglesVector;
  77041. }
  77042. for (i = 0; i < this.vertices.length; ++i) {
  77043. this.vertices[i].triangleCount = 0;
  77044. this.vertices[i].triangleStart = 0;
  77045. }
  77046. var t;
  77047. var j;
  77048. var v;
  77049. for (i = 0; i < this.triangles.length; ++i) {
  77050. t = this.triangles[i];
  77051. for (j = 0; j < 3; ++j) {
  77052. v = t.vertices[j];
  77053. v.triangleCount++;
  77054. }
  77055. }
  77056. var tStart = 0;
  77057. for (i = 0; i < this.vertices.length; ++i) {
  77058. this.vertices[i].triangleStart = tStart;
  77059. tStart += this.vertices[i].triangleCount;
  77060. this.vertices[i].triangleCount = 0;
  77061. }
  77062. var newReferences = new Array(this.triangles.length * 3);
  77063. for (i = 0; i < this.triangles.length; ++i) {
  77064. t = this.triangles[i];
  77065. for (j = 0; j < 3; ++j) {
  77066. v = t.vertices[j];
  77067. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  77068. v.triangleCount++;
  77069. }
  77070. }
  77071. this.references = newReferences;
  77072. if (identifyBorders) {
  77073. this.identifyBorder();
  77074. }
  77075. };
  77076. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  77077. var x = point.x;
  77078. var y = point.y;
  77079. var z = point.z;
  77080. 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
  77081. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  77082. };
  77083. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  77084. var q = vertex1.q.add(vertex2.q);
  77085. var border = vertex1.isBorder && vertex2.isBorder;
  77086. var error = 0;
  77087. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  77088. if (qDet !== 0 && !border) {
  77089. if (!pointResult) {
  77090. pointResult = BABYLON.Vector3.Zero();
  77091. }
  77092. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  77093. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  77094. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  77095. error = this.vertexError(q, pointResult);
  77096. }
  77097. else {
  77098. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  77099. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  77100. var error1 = this.vertexError(q, vertex1.position);
  77101. var error2 = this.vertexError(q, vertex2.position);
  77102. var error3 = this.vertexError(q, p3);
  77103. error = Math.min(error1, error2, error3);
  77104. if (error === error1) {
  77105. if (pointResult) {
  77106. pointResult.copyFrom(vertex1.position);
  77107. }
  77108. }
  77109. else if (error === error2) {
  77110. if (pointResult) {
  77111. pointResult.copyFrom(vertex2.position);
  77112. }
  77113. }
  77114. else {
  77115. if (pointResult) {
  77116. pointResult.copyFrom(p3);
  77117. }
  77118. }
  77119. }
  77120. return error;
  77121. };
  77122. return QuadraticErrorSimplification;
  77123. }());
  77124. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  77125. })(BABYLON || (BABYLON = {}));
  77126. //# sourceMappingURL=babylon.meshSimplification.js.map
  77127. var BABYLON;
  77128. (function (BABYLON) {
  77129. var MeshLODLevel = /** @class */ (function () {
  77130. function MeshLODLevel(distance, mesh) {
  77131. this.distance = distance;
  77132. this.mesh = mesh;
  77133. }
  77134. return MeshLODLevel;
  77135. }());
  77136. BABYLON.MeshLODLevel = MeshLODLevel;
  77137. })(BABYLON || (BABYLON = {}));
  77138. //# sourceMappingURL=babylon.meshLODLevel.js.map
  77139. var BABYLON;
  77140. (function (BABYLON) {
  77141. /**
  77142. * Defines the root class used to create scene optimization to use with SceneOptimizer
  77143. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77144. */
  77145. var SceneOptimization = /** @class */ (function () {
  77146. /**
  77147. * Creates the SceneOptimization object
  77148. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77149. * @param desc defines the description associated with the optimization
  77150. */
  77151. function SceneOptimization(
  77152. /**
  77153. * Defines the priority of this optimization (0 by default which means first in the list)
  77154. */
  77155. priority) {
  77156. if (priority === void 0) { priority = 0; }
  77157. this.priority = priority;
  77158. }
  77159. /**
  77160. * Gets a string describing the action executed by the current optimization
  77161. * @returns description string
  77162. */
  77163. SceneOptimization.prototype.getDescription = function () {
  77164. return "";
  77165. };
  77166. /**
  77167. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77168. * @param scene defines the current scene where to apply this optimization
  77169. * @param optimizer defines the current optimizer
  77170. * @returns true if everything that can be done was applied
  77171. */
  77172. SceneOptimization.prototype.apply = function (scene, optimizer) {
  77173. return true;
  77174. };
  77175. ;
  77176. return SceneOptimization;
  77177. }());
  77178. BABYLON.SceneOptimization = SceneOptimization;
  77179. /**
  77180. * Defines an optimization used to reduce the size of render target textures
  77181. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77182. */
  77183. var TextureOptimization = /** @class */ (function (_super) {
  77184. __extends(TextureOptimization, _super);
  77185. /**
  77186. * Creates the TextureOptimization object
  77187. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77188. * @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
  77189. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77190. */
  77191. function TextureOptimization(
  77192. /**
  77193. * Defines the priority of this optimization (0 by default which means first in the list)
  77194. */
  77195. priority,
  77196. /**
  77197. * 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
  77198. */
  77199. maximumSize,
  77200. /**
  77201. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77202. */
  77203. step) {
  77204. if (priority === void 0) { priority = 0; }
  77205. if (maximumSize === void 0) { maximumSize = 1024; }
  77206. if (step === void 0) { step = 0.5; }
  77207. var _this = _super.call(this, priority) || this;
  77208. _this.priority = priority;
  77209. _this.maximumSize = maximumSize;
  77210. _this.step = step;
  77211. return _this;
  77212. }
  77213. /**
  77214. * Gets a string describing the action executed by the current optimization
  77215. * @returns description string
  77216. */
  77217. TextureOptimization.prototype.getDescription = function () {
  77218. return "Reducing render target texture size to " + this.maximumSize;
  77219. };
  77220. /**
  77221. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77222. * @param scene defines the current scene where to apply this optimization
  77223. * @param optimizer defines the current optimizer
  77224. * @returns true if everything that can be done was applied
  77225. */
  77226. TextureOptimization.prototype.apply = function (scene, optimizer) {
  77227. var allDone = true;
  77228. for (var index = 0; index < scene.textures.length; index++) {
  77229. var texture = scene.textures[index];
  77230. if (!texture.canRescale || texture.getContext) {
  77231. continue;
  77232. }
  77233. var currentSize = texture.getSize();
  77234. var maxDimension = Math.max(currentSize.width, currentSize.height);
  77235. if (maxDimension > this.maximumSize) {
  77236. texture.scale(this.step);
  77237. allDone = false;
  77238. }
  77239. }
  77240. return allDone;
  77241. };
  77242. return TextureOptimization;
  77243. }(SceneOptimization));
  77244. BABYLON.TextureOptimization = TextureOptimization;
  77245. /**
  77246. * Defines an optimization used to increase or decrease the rendering resolution
  77247. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77248. */
  77249. var HardwareScalingOptimization = /** @class */ (function (_super) {
  77250. __extends(HardwareScalingOptimization, _super);
  77251. /**
  77252. * Creates the HardwareScalingOptimization object
  77253. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77254. * @param maximumScale defines the maximum scale to use (2 by default)
  77255. * @param step defines the step to use between two passes (0.5 by default)
  77256. */
  77257. function HardwareScalingOptimization(
  77258. /**
  77259. * Defines the priority of this optimization (0 by default which means first in the list)
  77260. */
  77261. priority,
  77262. /**
  77263. * Defines the maximum scale to use (2 by default)
  77264. */
  77265. maximumScale,
  77266. /**
  77267. * Defines the step to use between two passes (0.5 by default)
  77268. */
  77269. step) {
  77270. if (priority === void 0) { priority = 0; }
  77271. if (maximumScale === void 0) { maximumScale = 2; }
  77272. if (step === void 0) { step = 0.25; }
  77273. var _this = _super.call(this, priority) || this;
  77274. _this.priority = priority;
  77275. _this.maximumScale = maximumScale;
  77276. _this.step = step;
  77277. _this._currentScale = -1;
  77278. _this._directionOffset = 1;
  77279. return _this;
  77280. }
  77281. /**
  77282. * Gets a string describing the action executed by the current optimization
  77283. * @return description string
  77284. */
  77285. HardwareScalingOptimization.prototype.getDescription = function () {
  77286. return "Setting hardware scaling level to " + this._currentScale;
  77287. };
  77288. /**
  77289. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77290. * @param scene defines the current scene where to apply this optimization
  77291. * @param optimizer defines the current optimizer
  77292. * @returns true if everything that can be done was applied
  77293. */
  77294. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  77295. if (this._currentScale === -1) {
  77296. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  77297. if (this._currentScale > this.maximumScale) {
  77298. this._directionOffset = -1;
  77299. }
  77300. }
  77301. this._currentScale += this._directionOffset * this.step;
  77302. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  77303. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  77304. };
  77305. ;
  77306. return HardwareScalingOptimization;
  77307. }(SceneOptimization));
  77308. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  77309. /**
  77310. * Defines an optimization used to remove shadows
  77311. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77312. */
  77313. var ShadowsOptimization = /** @class */ (function (_super) {
  77314. __extends(ShadowsOptimization, _super);
  77315. function ShadowsOptimization() {
  77316. return _super !== null && _super.apply(this, arguments) || this;
  77317. }
  77318. /**
  77319. * Gets a string describing the action executed by the current optimization
  77320. * @return description string
  77321. */
  77322. ShadowsOptimization.prototype.getDescription = function () {
  77323. return "Turning shadows on/off";
  77324. };
  77325. /**
  77326. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77327. * @param scene defines the current scene where to apply this optimization
  77328. * @param optimizer defines the current optimizer
  77329. * @returns true if everything that can be done was applied
  77330. */
  77331. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  77332. scene.shadowsEnabled = optimizer.isInImprovementMode;
  77333. return true;
  77334. };
  77335. ;
  77336. return ShadowsOptimization;
  77337. }(SceneOptimization));
  77338. BABYLON.ShadowsOptimization = ShadowsOptimization;
  77339. /**
  77340. * Defines an optimization used to turn post-processes off
  77341. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77342. */
  77343. var PostProcessesOptimization = /** @class */ (function (_super) {
  77344. __extends(PostProcessesOptimization, _super);
  77345. function PostProcessesOptimization() {
  77346. return _super !== null && _super.apply(this, arguments) || this;
  77347. }
  77348. /**
  77349. * Gets a string describing the action executed by the current optimization
  77350. * @return description string
  77351. */
  77352. PostProcessesOptimization.prototype.getDescription = function () {
  77353. return "Turning post-processes on/off";
  77354. };
  77355. /**
  77356. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77357. * @param scene defines the current scene where to apply this optimization
  77358. * @param optimizer defines the current optimizer
  77359. * @returns true if everything that can be done was applied
  77360. */
  77361. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  77362. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  77363. return true;
  77364. };
  77365. ;
  77366. return PostProcessesOptimization;
  77367. }(SceneOptimization));
  77368. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  77369. /**
  77370. * Defines an optimization used to turn lens flares off
  77371. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77372. */
  77373. var LensFlaresOptimization = /** @class */ (function (_super) {
  77374. __extends(LensFlaresOptimization, _super);
  77375. function LensFlaresOptimization() {
  77376. return _super !== null && _super.apply(this, arguments) || this;
  77377. }
  77378. /**
  77379. * Gets a string describing the action executed by the current optimization
  77380. * @return description string
  77381. */
  77382. LensFlaresOptimization.prototype.getDescription = function () {
  77383. return "Turning lens flares on/off";
  77384. };
  77385. /**
  77386. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77387. * @param scene defines the current scene where to apply this optimization
  77388. * @param optimizer defines the current optimizer
  77389. * @returns true if everything that can be done was applied
  77390. */
  77391. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  77392. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  77393. return true;
  77394. };
  77395. ;
  77396. return LensFlaresOptimization;
  77397. }(SceneOptimization));
  77398. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  77399. /**
  77400. * Defines an optimization based on user defined callback.
  77401. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77402. */
  77403. var CustomOptimization = /** @class */ (function (_super) {
  77404. __extends(CustomOptimization, _super);
  77405. function CustomOptimization() {
  77406. return _super !== null && _super.apply(this, arguments) || this;
  77407. }
  77408. /**
  77409. * Gets a string describing the action executed by the current optimization
  77410. * @returns description string
  77411. */
  77412. CustomOptimization.prototype.getDescription = function () {
  77413. if (this.onGetDescription) {
  77414. return this.onGetDescription();
  77415. }
  77416. return "Running user defined callback";
  77417. };
  77418. /**
  77419. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77420. * @param scene defines the current scene where to apply this optimization
  77421. * @param optimizer defines the current optimizer
  77422. * @returns true if everything that can be done was applied
  77423. */
  77424. CustomOptimization.prototype.apply = function (scene, optimizer) {
  77425. if (this.onApply) {
  77426. return this.onApply(scene, optimizer);
  77427. }
  77428. return true;
  77429. };
  77430. ;
  77431. return CustomOptimization;
  77432. }(SceneOptimization));
  77433. BABYLON.CustomOptimization = CustomOptimization;
  77434. /**
  77435. * Defines an optimization used to turn particles off
  77436. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77437. */
  77438. var ParticlesOptimization = /** @class */ (function (_super) {
  77439. __extends(ParticlesOptimization, _super);
  77440. function ParticlesOptimization() {
  77441. return _super !== null && _super.apply(this, arguments) || this;
  77442. }
  77443. /**
  77444. * Gets a string describing the action executed by the current optimization
  77445. * @return description string
  77446. */
  77447. ParticlesOptimization.prototype.getDescription = function () {
  77448. return "Turning particles on/off";
  77449. };
  77450. /**
  77451. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77452. * @param scene defines the current scene where to apply this optimization
  77453. * @param optimizer defines the current optimizer
  77454. * @returns true if everything that can be done was applied
  77455. */
  77456. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  77457. scene.particlesEnabled = optimizer.isInImprovementMode;
  77458. return true;
  77459. };
  77460. ;
  77461. return ParticlesOptimization;
  77462. }(SceneOptimization));
  77463. BABYLON.ParticlesOptimization = ParticlesOptimization;
  77464. /**
  77465. * Defines an optimization used to turn render targets off
  77466. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77467. */
  77468. var RenderTargetsOptimization = /** @class */ (function (_super) {
  77469. __extends(RenderTargetsOptimization, _super);
  77470. function RenderTargetsOptimization() {
  77471. return _super !== null && _super.apply(this, arguments) || this;
  77472. }
  77473. /**
  77474. * Gets a string describing the action executed by the current optimization
  77475. * @return description string
  77476. */
  77477. RenderTargetsOptimization.prototype.getDescription = function () {
  77478. return "Turning render targets off";
  77479. };
  77480. /**
  77481. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77482. * @param scene defines the current scene where to apply this optimization
  77483. * @param optimizer defines the current optimizer
  77484. * @returns true if everything that can be done was applied
  77485. */
  77486. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  77487. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  77488. return true;
  77489. };
  77490. ;
  77491. return RenderTargetsOptimization;
  77492. }(SceneOptimization));
  77493. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  77494. /**
  77495. * Defines an optimization used to merge meshes with compatible materials
  77496. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77497. */
  77498. var MergeMeshesOptimization = /** @class */ (function (_super) {
  77499. __extends(MergeMeshesOptimization, _super);
  77500. function MergeMeshesOptimization() {
  77501. var _this = _super !== null && _super.apply(this, arguments) || this;
  77502. _this._canBeMerged = function (abstractMesh) {
  77503. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  77504. return false;
  77505. }
  77506. var mesh = abstractMesh;
  77507. if (!mesh.isVisible || !mesh.isEnabled()) {
  77508. return false;
  77509. }
  77510. if (mesh.instances.length > 0) {
  77511. return false;
  77512. }
  77513. if (mesh.skeleton || mesh.hasLODLevels) {
  77514. return false;
  77515. }
  77516. if (mesh.parent) {
  77517. return false;
  77518. }
  77519. return true;
  77520. };
  77521. return _this;
  77522. }
  77523. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  77524. /**
  77525. * Gets or sets a boolean which defines if optimization octree has to be updated
  77526. */
  77527. get: function () {
  77528. return MergeMeshesOptimization._UpdateSelectionTree;
  77529. },
  77530. /**
  77531. * Gets or sets a boolean which defines if optimization octree has to be updated
  77532. */
  77533. set: function (value) {
  77534. MergeMeshesOptimization._UpdateSelectionTree = value;
  77535. },
  77536. enumerable: true,
  77537. configurable: true
  77538. });
  77539. /**
  77540. * Gets a string describing the action executed by the current optimization
  77541. * @return description string
  77542. */
  77543. MergeMeshesOptimization.prototype.getDescription = function () {
  77544. return "Merging similar meshes together";
  77545. };
  77546. /**
  77547. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77548. * @param scene defines the current scene where to apply this optimization
  77549. * @param optimizer defines the current optimizer
  77550. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  77551. * @returns true if everything that can be done was applied
  77552. */
  77553. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  77554. var globalPool = scene.meshes.slice(0);
  77555. var globalLength = globalPool.length;
  77556. for (var index = 0; index < globalLength; index++) {
  77557. var currentPool = new Array();
  77558. var current = globalPool[index];
  77559. // Checks
  77560. if (!this._canBeMerged(current)) {
  77561. continue;
  77562. }
  77563. currentPool.push(current);
  77564. // Find compatible meshes
  77565. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  77566. var otherMesh = globalPool[subIndex];
  77567. if (!this._canBeMerged(otherMesh)) {
  77568. continue;
  77569. }
  77570. if (otherMesh.material !== current.material) {
  77571. continue;
  77572. }
  77573. if (otherMesh.checkCollisions !== current.checkCollisions) {
  77574. continue;
  77575. }
  77576. currentPool.push(otherMesh);
  77577. globalLength--;
  77578. globalPool.splice(subIndex, 1);
  77579. subIndex--;
  77580. }
  77581. if (currentPool.length < 2) {
  77582. continue;
  77583. }
  77584. // Merge meshes
  77585. BABYLON.Mesh.MergeMeshes(currentPool);
  77586. }
  77587. if (updateSelectionTree != undefined) {
  77588. if (updateSelectionTree) {
  77589. scene.createOrUpdateSelectionOctree();
  77590. }
  77591. }
  77592. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  77593. scene.createOrUpdateSelectionOctree();
  77594. }
  77595. return true;
  77596. };
  77597. ;
  77598. MergeMeshesOptimization._UpdateSelectionTree = false;
  77599. return MergeMeshesOptimization;
  77600. }(SceneOptimization));
  77601. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  77602. /**
  77603. * Defines a list of options used by SceneOptimizer
  77604. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77605. */
  77606. var SceneOptimizerOptions = /** @class */ (function () {
  77607. /**
  77608. * Creates a new list of options used by SceneOptimizer
  77609. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  77610. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  77611. */
  77612. function SceneOptimizerOptions(
  77613. /**
  77614. * Defines the target frame rate to reach (60 by default)
  77615. */
  77616. targetFrameRate,
  77617. /**
  77618. * Defines the interval between two checkes (2000ms by default)
  77619. */
  77620. trackerDuration) {
  77621. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  77622. if (trackerDuration === void 0) { trackerDuration = 2000; }
  77623. this.targetFrameRate = targetFrameRate;
  77624. this.trackerDuration = trackerDuration;
  77625. /**
  77626. * Gets the list of optimizations to apply
  77627. */
  77628. this.optimizations = new Array();
  77629. }
  77630. /**
  77631. * Add a new optimization
  77632. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  77633. * @returns the current SceneOptimizerOptions
  77634. */
  77635. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  77636. this.optimizations.push(optimization);
  77637. return this;
  77638. };
  77639. /**
  77640. * Add a new custom optimization
  77641. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  77642. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  77643. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77644. * @returns the current SceneOptimizerOptions
  77645. */
  77646. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  77647. if (priority === void 0) { priority = 0; }
  77648. var optimization = new CustomOptimization(priority);
  77649. optimization.onApply = onApply;
  77650. optimization.onGetDescription = onGetDescription;
  77651. this.optimizations.push(optimization);
  77652. return this;
  77653. };
  77654. /**
  77655. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  77656. * @param targetFrameRate defines the target frame rate (60 by default)
  77657. * @returns a SceneOptimizerOptions object
  77658. */
  77659. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  77660. var result = new SceneOptimizerOptions(targetFrameRate);
  77661. var priority = 0;
  77662. result.addOptimization(new MergeMeshesOptimization(priority));
  77663. result.addOptimization(new ShadowsOptimization(priority));
  77664. result.addOptimization(new LensFlaresOptimization(priority));
  77665. // Next priority
  77666. priority++;
  77667. result.addOptimization(new PostProcessesOptimization(priority));
  77668. result.addOptimization(new ParticlesOptimization(priority));
  77669. // Next priority
  77670. priority++;
  77671. result.addOptimization(new TextureOptimization(priority, 1024));
  77672. return result;
  77673. };
  77674. /**
  77675. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  77676. * @param targetFrameRate defines the target frame rate (60 by default)
  77677. * @returns a SceneOptimizerOptions object
  77678. */
  77679. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  77680. var result = new SceneOptimizerOptions(targetFrameRate);
  77681. var priority = 0;
  77682. result.addOptimization(new MergeMeshesOptimization(priority));
  77683. result.addOptimization(new ShadowsOptimization(priority));
  77684. result.addOptimization(new LensFlaresOptimization(priority));
  77685. // Next priority
  77686. priority++;
  77687. result.addOptimization(new PostProcessesOptimization(priority));
  77688. result.addOptimization(new ParticlesOptimization(priority));
  77689. // Next priority
  77690. priority++;
  77691. result.addOptimization(new TextureOptimization(priority, 512));
  77692. // Next priority
  77693. priority++;
  77694. result.addOptimization(new RenderTargetsOptimization(priority));
  77695. // Next priority
  77696. priority++;
  77697. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  77698. return result;
  77699. };
  77700. /**
  77701. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  77702. * @param targetFrameRate defines the target frame rate (60 by default)
  77703. * @returns a SceneOptimizerOptions object
  77704. */
  77705. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  77706. var result = new SceneOptimizerOptions(targetFrameRate);
  77707. var priority = 0;
  77708. result.addOptimization(new MergeMeshesOptimization(priority));
  77709. result.addOptimization(new ShadowsOptimization(priority));
  77710. result.addOptimization(new LensFlaresOptimization(priority));
  77711. // Next priority
  77712. priority++;
  77713. result.addOptimization(new PostProcessesOptimization(priority));
  77714. result.addOptimization(new ParticlesOptimization(priority));
  77715. // Next priority
  77716. priority++;
  77717. result.addOptimization(new TextureOptimization(priority, 256));
  77718. // Next priority
  77719. priority++;
  77720. result.addOptimization(new RenderTargetsOptimization(priority));
  77721. // Next priority
  77722. priority++;
  77723. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  77724. return result;
  77725. };
  77726. return SceneOptimizerOptions;
  77727. }());
  77728. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  77729. /**
  77730. * Class used to run optimizations in order to reach a target frame rate
  77731. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77732. */
  77733. var SceneOptimizer = /** @class */ (function () {
  77734. /**
  77735. * Creates a new SceneOptimizer
  77736. * @param scene defines the scene to work on
  77737. * @param options defines the options to use with the SceneOptimizer
  77738. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  77739. * @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)
  77740. */
  77741. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  77742. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  77743. if (improvementMode === void 0) { improvementMode = false; }
  77744. var _this = this;
  77745. this._isRunning = false;
  77746. this._currentPriorityLevel = 0;
  77747. this._targetFrameRate = 60;
  77748. this._trackerDuration = 2000;
  77749. this._currentFrameRate = 0;
  77750. this._improvementMode = false;
  77751. /**
  77752. * Defines an observable called when the optimizer reaches the target frame rate
  77753. */
  77754. this.onSuccessObservable = new BABYLON.Observable();
  77755. /**
  77756. * Defines an observable called when the optimizer enables an optimization
  77757. */
  77758. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  77759. /**
  77760. * Defines an observable called when the optimizer is not able to reach the target frame rate
  77761. */
  77762. this.onFailureObservable = new BABYLON.Observable();
  77763. if (!options) {
  77764. this._options = new SceneOptimizerOptions();
  77765. }
  77766. else {
  77767. this._options = options;
  77768. }
  77769. if (this._options.targetFrameRate) {
  77770. this._targetFrameRate = this._options.targetFrameRate;
  77771. }
  77772. if (this._options.trackerDuration) {
  77773. this._trackerDuration = this._options.trackerDuration;
  77774. }
  77775. if (autoGeneratePriorities) {
  77776. var priority = 0;
  77777. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  77778. var optim = _a[_i];
  77779. optim.priority = priority++;
  77780. }
  77781. }
  77782. this._improvementMode = improvementMode;
  77783. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77784. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  77785. _this._sceneDisposeObserver = null;
  77786. _this.dispose();
  77787. });
  77788. }
  77789. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  77790. /**
  77791. * Gets a boolean indicating if the optimizer is in improvement mode
  77792. */
  77793. get: function () {
  77794. return this._improvementMode;
  77795. },
  77796. enumerable: true,
  77797. configurable: true
  77798. });
  77799. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  77800. /**
  77801. * Gets the current priority level (0 at start)
  77802. */
  77803. get: function () {
  77804. return this._currentPriorityLevel;
  77805. },
  77806. enumerable: true,
  77807. configurable: true
  77808. });
  77809. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  77810. /**
  77811. * Gets the current frame rate checked by the SceneOptimizer
  77812. */
  77813. get: function () {
  77814. return this._currentFrameRate;
  77815. },
  77816. enumerable: true,
  77817. configurable: true
  77818. });
  77819. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  77820. /**
  77821. * Gets or sets the current target frame rate (60 by default)
  77822. */
  77823. get: function () {
  77824. return this._targetFrameRate;
  77825. },
  77826. /**
  77827. * Gets or sets the current target frame rate (60 by default)
  77828. */
  77829. set: function (value) {
  77830. this._targetFrameRate = value;
  77831. },
  77832. enumerable: true,
  77833. configurable: true
  77834. });
  77835. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  77836. /**
  77837. * Gets or sets the current interval between two checks (every 2000ms by default)
  77838. */
  77839. get: function () {
  77840. return this._trackerDuration;
  77841. },
  77842. /**
  77843. * Gets or sets the current interval between two checks (every 2000ms by default)
  77844. */
  77845. set: function (value) {
  77846. this._trackerDuration = value;
  77847. },
  77848. enumerable: true,
  77849. configurable: true
  77850. });
  77851. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  77852. /**
  77853. * Gets the list of active optimizations
  77854. */
  77855. get: function () {
  77856. return this._options.optimizations;
  77857. },
  77858. enumerable: true,
  77859. configurable: true
  77860. });
  77861. /**
  77862. * Stops the current optimizer
  77863. */
  77864. SceneOptimizer.prototype.stop = function () {
  77865. this._isRunning = false;
  77866. };
  77867. /**
  77868. * Reset the optimizer to initial step (current priority level = 0)
  77869. */
  77870. SceneOptimizer.prototype.reset = function () {
  77871. this._currentPriorityLevel = 0;
  77872. };
  77873. /**
  77874. * Start the optimizer. By default it will try to reach a specific framerate
  77875. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  77876. */
  77877. SceneOptimizer.prototype.start = function () {
  77878. var _this = this;
  77879. if (this._isRunning) {
  77880. return;
  77881. }
  77882. this._isRunning = true;
  77883. // Let's wait for the scene to be ready before running our check
  77884. this._scene.executeWhenReady(function () {
  77885. setTimeout(function () {
  77886. _this._checkCurrentState();
  77887. }, _this._trackerDuration);
  77888. });
  77889. };
  77890. SceneOptimizer.prototype._checkCurrentState = function () {
  77891. var _this = this;
  77892. if (!this._isRunning) {
  77893. return;
  77894. }
  77895. var scene = this._scene;
  77896. var options = this._options;
  77897. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  77898. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  77899. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  77900. this._isRunning = false;
  77901. this.onSuccessObservable.notifyObservers(this);
  77902. return;
  77903. }
  77904. // Apply current level of optimizations
  77905. var allDone = true;
  77906. var noOptimizationApplied = true;
  77907. for (var index = 0; index < options.optimizations.length; index++) {
  77908. var optimization = options.optimizations[index];
  77909. if (optimization.priority === this._currentPriorityLevel) {
  77910. noOptimizationApplied = false;
  77911. allDone = allDone && optimization.apply(scene, this);
  77912. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  77913. }
  77914. }
  77915. // If no optimization was applied, this is a failure :(
  77916. if (noOptimizationApplied) {
  77917. this._isRunning = false;
  77918. this.onFailureObservable.notifyObservers(this);
  77919. return;
  77920. }
  77921. // If all optimizations were done, move to next level
  77922. if (allDone) {
  77923. this._currentPriorityLevel++;
  77924. }
  77925. // Let's the system running for a specific amount of time before checking FPS
  77926. scene.executeWhenReady(function () {
  77927. setTimeout(function () {
  77928. _this._checkCurrentState();
  77929. }, _this._trackerDuration);
  77930. });
  77931. };
  77932. /**
  77933. * Release all resources
  77934. */
  77935. SceneOptimizer.prototype.dispose = function () {
  77936. this.stop();
  77937. this.onSuccessObservable.clear();
  77938. this.onFailureObservable.clear();
  77939. this.onNewOptimizationAppliedObservable.clear();
  77940. if (this._sceneDisposeObserver) {
  77941. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  77942. }
  77943. };
  77944. /**
  77945. * Helper function to create a SceneOptimizer with one single line of code
  77946. * @param scene defines the scene to work on
  77947. * @param options defines the options to use with the SceneOptimizer
  77948. * @param onSuccess defines a callback to call on success
  77949. * @param onFailure defines a callback to call on failure
  77950. * @returns the new SceneOptimizer object
  77951. */
  77952. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  77953. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  77954. if (onSuccess) {
  77955. optimizer.onSuccessObservable.add(function () {
  77956. onSuccess();
  77957. });
  77958. }
  77959. if (onFailure) {
  77960. optimizer.onFailureObservable.add(function () {
  77961. onFailure();
  77962. });
  77963. }
  77964. optimizer.start();
  77965. return optimizer;
  77966. };
  77967. return SceneOptimizer;
  77968. }());
  77969. BABYLON.SceneOptimizer = SceneOptimizer;
  77970. })(BABYLON || (BABYLON = {}));
  77971. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  77972. var BABYLON;
  77973. (function (BABYLON) {
  77974. var OutlineRenderer = /** @class */ (function () {
  77975. function OutlineRenderer(scene) {
  77976. this.zOffset = 1;
  77977. this._scene = scene;
  77978. }
  77979. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  77980. var _this = this;
  77981. if (useOverlay === void 0) { useOverlay = false; }
  77982. var scene = this._scene;
  77983. var engine = this._scene.getEngine();
  77984. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  77985. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  77986. return;
  77987. }
  77988. var mesh = subMesh.getRenderingMesh();
  77989. var material = subMesh.getMaterial();
  77990. if (!material || !scene.activeCamera) {
  77991. return;
  77992. }
  77993. engine.enableEffect(this._effect);
  77994. // Logarithmic depth
  77995. if (material.useLogarithmicDepth) {
  77996. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  77997. }
  77998. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  77999. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78000. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78001. // Bones
  78002. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78003. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78004. }
  78005. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78006. // Alpha test
  78007. if (material && material.needAlphaTesting()) {
  78008. var alphaTexture = material.getAlphaTestTexture();
  78009. if (alphaTexture) {
  78010. this._effect.setTexture("diffuseSampler", alphaTexture);
  78011. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78012. }
  78013. }
  78014. engine.setZOffset(-this.zOffset);
  78015. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78016. engine.setZOffset(0);
  78017. };
  78018. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78019. var defines = [];
  78020. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78021. var mesh = subMesh.getMesh();
  78022. var material = subMesh.getMaterial();
  78023. if (material) {
  78024. // Alpha test
  78025. if (material.needAlphaTesting()) {
  78026. defines.push("#define ALPHATEST");
  78027. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78028. attribs.push(BABYLON.VertexBuffer.UVKind);
  78029. defines.push("#define UV1");
  78030. }
  78031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78032. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78033. defines.push("#define UV2");
  78034. }
  78035. }
  78036. //Logarithmic depth
  78037. if (material.useLogarithmicDepth) {
  78038. defines.push("#define LOGARITHMICDEPTH");
  78039. }
  78040. }
  78041. // Bones
  78042. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78043. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78044. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78045. if (mesh.numBoneInfluencers > 4) {
  78046. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78047. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78048. }
  78049. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78050. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78051. }
  78052. else {
  78053. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78054. }
  78055. // Instances
  78056. if (useInstances) {
  78057. defines.push("#define INSTANCES");
  78058. attribs.push("world0");
  78059. attribs.push("world1");
  78060. attribs.push("world2");
  78061. attribs.push("world3");
  78062. }
  78063. // Get correct effect
  78064. var join = defines.join("\n");
  78065. if (this._cachedDefines !== join) {
  78066. this._cachedDefines = join;
  78067. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  78068. }
  78069. return this._effect.isReady();
  78070. };
  78071. return OutlineRenderer;
  78072. }());
  78073. BABYLON.OutlineRenderer = OutlineRenderer;
  78074. })(BABYLON || (BABYLON = {}));
  78075. //# sourceMappingURL=babylon.outlineRenderer.js.map
  78076. var BABYLON;
  78077. (function (BABYLON) {
  78078. var FaceAdjacencies = /** @class */ (function () {
  78079. function FaceAdjacencies() {
  78080. this.edges = new Array();
  78081. this.edgesConnectedCount = 0;
  78082. }
  78083. return FaceAdjacencies;
  78084. }());
  78085. var EdgesRenderer = /** @class */ (function () {
  78086. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  78087. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  78088. if (epsilon === void 0) { epsilon = 0.95; }
  78089. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  78090. this.edgesWidthScalerForOrthographic = 1000.0;
  78091. this.edgesWidthScalerForPerspective = 50.0;
  78092. this._linesPositions = new Array();
  78093. this._linesNormals = new Array();
  78094. this._linesIndices = new Array();
  78095. this._buffers = {};
  78096. this._checkVerticesInsteadOfIndices = false;
  78097. this._source = source;
  78098. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  78099. this._epsilon = epsilon;
  78100. this._prepareRessources();
  78101. this._generateEdgesLines();
  78102. }
  78103. EdgesRenderer.prototype._prepareRessources = function () {
  78104. if (this._lineShader) {
  78105. return;
  78106. }
  78107. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  78108. attributes: ["position", "normal"],
  78109. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  78110. });
  78111. this._lineShader.disableDepthWrite = true;
  78112. this._lineShader.backFaceCulling = false;
  78113. };
  78114. EdgesRenderer.prototype._rebuild = function () {
  78115. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78116. if (buffer) {
  78117. buffer._rebuild();
  78118. }
  78119. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78120. if (buffer) {
  78121. buffer._rebuild();
  78122. }
  78123. var scene = this._source.getScene();
  78124. var engine = scene.getEngine();
  78125. this._ib = engine.createIndexBuffer(this._linesIndices);
  78126. };
  78127. EdgesRenderer.prototype.dispose = function () {
  78128. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78129. if (buffer) {
  78130. buffer.dispose();
  78131. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  78132. }
  78133. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78134. if (buffer) {
  78135. buffer.dispose();
  78136. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  78137. }
  78138. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  78139. this._lineShader.dispose();
  78140. };
  78141. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  78142. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  78143. return 0;
  78144. }
  78145. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  78146. return 1;
  78147. }
  78148. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  78149. return 2;
  78150. }
  78151. return -1;
  78152. };
  78153. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  78154. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  78155. return 0;
  78156. }
  78157. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  78158. return 1;
  78159. }
  78160. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  78161. return 2;
  78162. }
  78163. return -1;
  78164. };
  78165. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  78166. var needToCreateLine;
  78167. if (edge === undefined) {
  78168. needToCreateLine = true;
  78169. }
  78170. else {
  78171. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  78172. needToCreateLine = dotProduct < this._epsilon;
  78173. }
  78174. if (needToCreateLine) {
  78175. var offset = this._linesPositions.length / 3;
  78176. var normal = p0.subtract(p1);
  78177. normal.normalize();
  78178. // Positions
  78179. this._linesPositions.push(p0.x);
  78180. this._linesPositions.push(p0.y);
  78181. this._linesPositions.push(p0.z);
  78182. this._linesPositions.push(p0.x);
  78183. this._linesPositions.push(p0.y);
  78184. this._linesPositions.push(p0.z);
  78185. this._linesPositions.push(p1.x);
  78186. this._linesPositions.push(p1.y);
  78187. this._linesPositions.push(p1.z);
  78188. this._linesPositions.push(p1.x);
  78189. this._linesPositions.push(p1.y);
  78190. this._linesPositions.push(p1.z);
  78191. // Normals
  78192. this._linesNormals.push(p1.x);
  78193. this._linesNormals.push(p1.y);
  78194. this._linesNormals.push(p1.z);
  78195. this._linesNormals.push(-1);
  78196. this._linesNormals.push(p1.x);
  78197. this._linesNormals.push(p1.y);
  78198. this._linesNormals.push(p1.z);
  78199. this._linesNormals.push(1);
  78200. this._linesNormals.push(p0.x);
  78201. this._linesNormals.push(p0.y);
  78202. this._linesNormals.push(p0.z);
  78203. this._linesNormals.push(-1);
  78204. this._linesNormals.push(p0.x);
  78205. this._linesNormals.push(p0.y);
  78206. this._linesNormals.push(p0.z);
  78207. this._linesNormals.push(1);
  78208. // Indices
  78209. this._linesIndices.push(offset);
  78210. this._linesIndices.push(offset + 1);
  78211. this._linesIndices.push(offset + 2);
  78212. this._linesIndices.push(offset);
  78213. this._linesIndices.push(offset + 2);
  78214. this._linesIndices.push(offset + 3);
  78215. }
  78216. };
  78217. EdgesRenderer.prototype._generateEdgesLines = function () {
  78218. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78219. var indices = this._source.getIndices();
  78220. if (!indices || !positions) {
  78221. return;
  78222. }
  78223. // First let's find adjacencies
  78224. var adjacencies = new Array();
  78225. var faceNormals = new Array();
  78226. var index;
  78227. var faceAdjacencies;
  78228. // Prepare faces
  78229. for (index = 0; index < indices.length; index += 3) {
  78230. faceAdjacencies = new FaceAdjacencies();
  78231. var p0Index = indices[index];
  78232. var p1Index = indices[index + 1];
  78233. var p2Index = indices[index + 2];
  78234. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  78235. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  78236. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  78237. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  78238. faceNormal.normalize();
  78239. faceNormals.push(faceNormal);
  78240. adjacencies.push(faceAdjacencies);
  78241. }
  78242. // Scan
  78243. for (index = 0; index < adjacencies.length; index++) {
  78244. faceAdjacencies = adjacencies[index];
  78245. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  78246. var otherFaceAdjacencies = adjacencies[otherIndex];
  78247. if (faceAdjacencies.edgesConnectedCount === 3) {
  78248. break;
  78249. }
  78250. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  78251. continue;
  78252. }
  78253. var otherP0 = indices[otherIndex * 3];
  78254. var otherP1 = indices[otherIndex * 3 + 1];
  78255. var otherP2 = indices[otherIndex * 3 + 2];
  78256. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  78257. var otherEdgeIndex = 0;
  78258. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  78259. continue;
  78260. }
  78261. switch (edgeIndex) {
  78262. case 0:
  78263. if (this._checkVerticesInsteadOfIndices) {
  78264. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78265. }
  78266. else {
  78267. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  78268. }
  78269. break;
  78270. case 1:
  78271. if (this._checkVerticesInsteadOfIndices) {
  78272. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78273. }
  78274. else {
  78275. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  78276. }
  78277. break;
  78278. case 2:
  78279. if (this._checkVerticesInsteadOfIndices) {
  78280. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78281. }
  78282. else {
  78283. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  78284. }
  78285. break;
  78286. }
  78287. if (otherEdgeIndex === -1) {
  78288. continue;
  78289. }
  78290. faceAdjacencies.edges[edgeIndex] = otherIndex;
  78291. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  78292. faceAdjacencies.edgesConnectedCount++;
  78293. otherFaceAdjacencies.edgesConnectedCount++;
  78294. if (faceAdjacencies.edgesConnectedCount === 3) {
  78295. break;
  78296. }
  78297. }
  78298. }
  78299. }
  78300. // Create lines
  78301. for (index = 0; index < adjacencies.length; index++) {
  78302. // 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
  78303. var current = adjacencies[index];
  78304. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  78305. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  78306. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  78307. }
  78308. // Merge into a single mesh
  78309. var engine = this._source.getScene().getEngine();
  78310. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  78311. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  78312. this._ib = engine.createIndexBuffer(this._linesIndices);
  78313. this._indicesCount = this._linesIndices.length;
  78314. };
  78315. EdgesRenderer.prototype.render = function () {
  78316. var scene = this._source.getScene();
  78317. if (!this._lineShader.isReady() || !scene.activeCamera) {
  78318. return;
  78319. }
  78320. var engine = scene.getEngine();
  78321. this._lineShader._preBind();
  78322. // VBOs
  78323. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  78324. scene.resetCachedMaterial();
  78325. this._lineShader.setColor4("color", this._source.edgesColor);
  78326. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  78327. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  78328. }
  78329. else {
  78330. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  78331. }
  78332. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  78333. this._lineShader.bind(this._source.getWorldMatrix());
  78334. // Draw order
  78335. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  78336. this._lineShader.unbind();
  78337. engine.setDepthWrite(true);
  78338. };
  78339. return EdgesRenderer;
  78340. }());
  78341. BABYLON.EdgesRenderer = EdgesRenderer;
  78342. })(BABYLON || (BABYLON = {}));
  78343. //# sourceMappingURL=babylon.edgesRenderer.js.map
  78344. var BABYLON;
  78345. (function (BABYLON) {
  78346. /**
  78347. * Special Glow Blur post process only blurring the alpha channel
  78348. * It enforces keeping the most luminous color in the color channel.
  78349. */
  78350. var GlowBlurPostProcess = /** @class */ (function (_super) {
  78351. __extends(GlowBlurPostProcess, _super);
  78352. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  78353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78354. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  78355. _this.direction = direction;
  78356. _this.kernel = kernel;
  78357. _this.onApplyObservable.add(function (effect) {
  78358. effect.setFloat2("screenSize", _this.width, _this.height);
  78359. effect.setVector2("direction", _this.direction);
  78360. effect.setFloat("blurWidth", _this.kernel);
  78361. });
  78362. return _this;
  78363. }
  78364. return GlowBlurPostProcess;
  78365. }(BABYLON.PostProcess));
  78366. /**
  78367. * The highlight layer Helps adding a glow effect around a mesh.
  78368. *
  78369. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  78370. * glowy meshes to your scene.
  78371. *
  78372. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  78373. */
  78374. var HighlightLayer = /** @class */ (function () {
  78375. /**
  78376. * Instantiates a new highlight Layer and references it to the scene..
  78377. * @param name The name of the layer
  78378. * @param scene The scene to use the layer in
  78379. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  78380. */
  78381. function HighlightLayer(name, scene, options) {
  78382. this.name = name;
  78383. this._vertexBuffers = {};
  78384. this._mainTextureDesiredSize = { width: 0, height: 0 };
  78385. this._meshes = {};
  78386. this._maxSize = 0;
  78387. this._shouldRender = false;
  78388. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  78389. this._excludedMeshes = {};
  78390. /**
  78391. * Specifies whether or not the inner glow is ACTIVE in the layer.
  78392. */
  78393. this.innerGlow = true;
  78394. /**
  78395. * Specifies whether or not the outer glow is ACTIVE in the layer.
  78396. */
  78397. this.outerGlow = true;
  78398. /**
  78399. * Specifies wether the highlight layer is enabled or not.
  78400. */
  78401. this.isEnabled = true;
  78402. /**
  78403. * An event triggered when the highlight layer has been disposed.
  78404. * @type {BABYLON.Observable}
  78405. */
  78406. this.onDisposeObservable = new BABYLON.Observable();
  78407. /**
  78408. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  78409. * @type {BABYLON.Observable}
  78410. */
  78411. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  78412. /**
  78413. * An event triggered when the highlight layer is being blurred.
  78414. * @type {BABYLON.Observable}
  78415. */
  78416. this.onBeforeBlurObservable = new BABYLON.Observable();
  78417. /**
  78418. * An event triggered when the highlight layer has been blurred.
  78419. * @type {BABYLON.Observable}
  78420. */
  78421. this.onAfterBlurObservable = new BABYLON.Observable();
  78422. /**
  78423. * An event triggered when the glowing blurred texture is being merged in the scene.
  78424. * @type {BABYLON.Observable}
  78425. */
  78426. this.onBeforeComposeObservable = new BABYLON.Observable();
  78427. /**
  78428. * An event triggered when the glowing blurred texture has been merged in the scene.
  78429. * @type {BABYLON.Observable}
  78430. */
  78431. this.onAfterComposeObservable = new BABYLON.Observable();
  78432. /**
  78433. * An event triggered when the highlight layer changes its size.
  78434. * @type {BABYLON.Observable}
  78435. */
  78436. this.onSizeChangedObservable = new BABYLON.Observable();
  78437. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78438. var engine = scene.getEngine();
  78439. this._engine = engine;
  78440. this._maxSize = this._engine.getCaps().maxTextureSize;
  78441. this._scene.highlightLayers.push(this);
  78442. // Warn on stencil.
  78443. if (!this._engine.isStencilEnable) {
  78444. 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 }");
  78445. }
  78446. // Adapt options
  78447. this._options = options || {
  78448. mainTextureRatio: 0.5,
  78449. blurTextureSizeRatio: 0.5,
  78450. blurHorizontalSize: 1.0,
  78451. blurVerticalSize: 1.0,
  78452. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  78453. camera: null
  78454. };
  78455. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  78456. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  78457. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  78458. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  78459. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  78460. // VBO
  78461. var vertices = [];
  78462. vertices.push(1, 1);
  78463. vertices.push(-1, 1);
  78464. vertices.push(-1, -1);
  78465. vertices.push(1, -1);
  78466. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78467. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78468. this._createIndexBuffer();
  78469. // Effect
  78470. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  78471. // Render target
  78472. this.setMainTextureSize();
  78473. // Create Textures and post processes
  78474. this.createTextureAndPostProcesses();
  78475. }
  78476. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  78477. /**
  78478. * Gets the horizontal size of the blur.
  78479. */
  78480. get: function () {
  78481. return this._horizontalBlurPostprocess.kernel;
  78482. },
  78483. /**
  78484. * Specifies the horizontal size of the blur.
  78485. */
  78486. set: function (value) {
  78487. this._horizontalBlurPostprocess.kernel = value;
  78488. },
  78489. enumerable: true,
  78490. configurable: true
  78491. });
  78492. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  78493. /**
  78494. * Gets the vertical size of the blur.
  78495. */
  78496. get: function () {
  78497. return this._verticalBlurPostprocess.kernel;
  78498. },
  78499. /**
  78500. * Specifies the vertical size of the blur.
  78501. */
  78502. set: function (value) {
  78503. this._verticalBlurPostprocess.kernel = value;
  78504. },
  78505. enumerable: true,
  78506. configurable: true
  78507. });
  78508. Object.defineProperty(HighlightLayer.prototype, "camera", {
  78509. /**
  78510. * Gets the camera attached to the layer.
  78511. */
  78512. get: function () {
  78513. return this._options.camera;
  78514. },
  78515. enumerable: true,
  78516. configurable: true
  78517. });
  78518. HighlightLayer.prototype._createIndexBuffer = function () {
  78519. var engine = this._scene.getEngine();
  78520. // Indices
  78521. var indices = [];
  78522. indices.push(0);
  78523. indices.push(1);
  78524. indices.push(2);
  78525. indices.push(0);
  78526. indices.push(2);
  78527. indices.push(3);
  78528. this._indexBuffer = engine.createIndexBuffer(indices);
  78529. };
  78530. HighlightLayer.prototype._rebuild = function () {
  78531. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78532. if (vb) {
  78533. vb._rebuild();
  78534. }
  78535. this._createIndexBuffer();
  78536. };
  78537. /**
  78538. * Creates the render target textures and post processes used in the highlight layer.
  78539. */
  78540. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  78541. var _this = this;
  78542. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  78543. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  78544. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  78545. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  78546. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  78547. width: this._mainTextureDesiredSize.width,
  78548. height: this._mainTextureDesiredSize.height
  78549. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78550. this._mainTexture.activeCamera = this._options.camera;
  78551. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78552. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78553. this._mainTexture.anisotropicFilteringLevel = 1;
  78554. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78555. this._mainTexture.renderParticles = false;
  78556. this._mainTexture.renderList = null;
  78557. this._mainTexture.ignoreCameraViewport = true;
  78558. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  78559. width: blurTextureWidth,
  78560. height: blurTextureHeight
  78561. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78562. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78563. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78564. this._blurTexture.anisotropicFilteringLevel = 16;
  78565. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78566. this._blurTexture.renderParticles = false;
  78567. this._blurTexture.ignoreCameraViewport = true;
  78568. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78569. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  78570. effect.setTexture("textureSampler", _this._mainTexture);
  78571. });
  78572. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  78573. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78574. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78575. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78576. });
  78577. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78578. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78579. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78580. });
  78581. }
  78582. else {
  78583. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78584. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  78585. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78586. });
  78587. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  78588. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  78589. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  78590. });
  78591. }
  78592. this._mainTexture.onAfterUnbindObservable.add(function () {
  78593. _this.onBeforeBlurObservable.notifyObservers(_this);
  78594. var internalTexture = _this._blurTexture.getInternalTexture();
  78595. if (internalTexture) {
  78596. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  78597. }
  78598. _this.onAfterBlurObservable.notifyObservers(_this);
  78599. });
  78600. // Custom render function
  78601. var renderSubMesh = function (subMesh) {
  78602. if (!_this._meshes) {
  78603. return;
  78604. }
  78605. var material = subMesh.getMaterial();
  78606. var mesh = subMesh.getRenderingMesh();
  78607. var scene = _this._scene;
  78608. var engine = scene.getEngine();
  78609. if (!material) {
  78610. return;
  78611. }
  78612. // Do not block in blend mode.
  78613. if (material.needAlphaBlendingForMesh(mesh)) {
  78614. return;
  78615. }
  78616. // Culling
  78617. engine.setState(material.backFaceCulling);
  78618. // Managing instances
  78619. var batch = mesh._getInstancesRenderList(subMesh._id);
  78620. if (batch.mustReturn) {
  78621. return;
  78622. }
  78623. // Excluded Mesh
  78624. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  78625. return;
  78626. }
  78627. ;
  78628. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78629. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  78630. var emissiveTexture = null;
  78631. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  78632. emissiveTexture = material.emissiveTexture;
  78633. }
  78634. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  78635. engine.enableEffect(_this._glowMapGenerationEffect);
  78636. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  78637. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  78638. if (highlightLayerMesh) {
  78639. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  78640. }
  78641. else {
  78642. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  78643. }
  78644. // Alpha test
  78645. if (material && material.needAlphaTesting()) {
  78646. var alphaTexture = material.getAlphaTestTexture();
  78647. if (alphaTexture) {
  78648. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  78649. var textureMatrix = alphaTexture.getTextureMatrix();
  78650. if (textureMatrix) {
  78651. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  78652. }
  78653. }
  78654. }
  78655. // Glow emissive only
  78656. if (emissiveTexture) {
  78657. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  78658. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  78659. }
  78660. // Bones
  78661. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78662. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78663. }
  78664. // Draw
  78665. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  78666. }
  78667. else {
  78668. // Need to reset refresh rate of the shadowMap
  78669. _this._mainTexture.resetRefreshCounter();
  78670. }
  78671. };
  78672. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78673. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  78674. var index;
  78675. var engine = _this._scene.getEngine();
  78676. if (depthOnlySubMeshes.length) {
  78677. engine.setColorWrite(false);
  78678. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78679. renderSubMesh(depthOnlySubMeshes.data[index]);
  78680. }
  78681. engine.setColorWrite(true);
  78682. }
  78683. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78684. renderSubMesh(opaqueSubMeshes.data[index]);
  78685. }
  78686. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78687. renderSubMesh(alphaTestSubMeshes.data[index]);
  78688. }
  78689. for (index = 0; index < transparentSubMeshes.length; index++) {
  78690. renderSubMesh(transparentSubMeshes.data[index]);
  78691. }
  78692. };
  78693. this._mainTexture.onClearObservable.add(function (engine) {
  78694. engine.clear(HighlightLayer.neutralColor, true, true, true);
  78695. });
  78696. };
  78697. /**
  78698. * Checks for the readiness of the element composing the layer.
  78699. * @param subMesh the mesh to check for
  78700. * @param useInstances specify wether or not to use instances to render the mesh
  78701. * @param emissiveTexture the associated emissive texture used to generate the glow
  78702. * @return true if ready otherwise, false
  78703. */
  78704. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  78705. var material = subMesh.getMaterial();
  78706. var mesh = subMesh.getRenderingMesh();
  78707. if (!material || !mesh || !this._meshes) {
  78708. return false;
  78709. }
  78710. var emissiveTexture = null;
  78711. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  78712. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  78713. emissiveTexture = material.emissiveTexture;
  78714. }
  78715. return this._isReady(subMesh, useInstances, emissiveTexture);
  78716. };
  78717. /**
  78718. * Checks for the readiness of the element composing the layer.
  78719. * @param subMesh the mesh to check for
  78720. * @param useInstances specify wether or not to use instances to render the mesh
  78721. * @param emissiveTexture the associated emissive texture used to generate the glow
  78722. * @return true if ready otherwise, false
  78723. */
  78724. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  78725. var material = subMesh.getMaterial();
  78726. if (!material) {
  78727. return false;
  78728. }
  78729. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  78730. return false;
  78731. }
  78732. var defines = [];
  78733. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78734. var mesh = subMesh.getMesh();
  78735. var uv1 = false;
  78736. var uv2 = false;
  78737. // Alpha test
  78738. if (material && material.needAlphaTesting()) {
  78739. var alphaTexture = material.getAlphaTestTexture();
  78740. if (alphaTexture) {
  78741. defines.push("#define ALPHATEST");
  78742. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  78743. alphaTexture.coordinatesIndex === 1) {
  78744. defines.push("#define DIFFUSEUV2");
  78745. uv2 = true;
  78746. }
  78747. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78748. defines.push("#define DIFFUSEUV1");
  78749. uv1 = true;
  78750. }
  78751. }
  78752. }
  78753. // Emissive
  78754. if (emissiveTexture) {
  78755. defines.push("#define EMISSIVE");
  78756. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  78757. emissiveTexture.coordinatesIndex === 1) {
  78758. defines.push("#define EMISSIVEUV2");
  78759. uv2 = true;
  78760. }
  78761. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78762. defines.push("#define EMISSIVEUV1");
  78763. uv1 = true;
  78764. }
  78765. }
  78766. if (uv1) {
  78767. attribs.push(BABYLON.VertexBuffer.UVKind);
  78768. defines.push("#define UV1");
  78769. }
  78770. if (uv2) {
  78771. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78772. defines.push("#define UV2");
  78773. }
  78774. // Bones
  78775. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78776. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78777. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78778. if (mesh.numBoneInfluencers > 4) {
  78779. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78780. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78781. }
  78782. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78783. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78784. }
  78785. else {
  78786. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78787. }
  78788. // Instances
  78789. if (useInstances) {
  78790. defines.push("#define INSTANCES");
  78791. attribs.push("world0");
  78792. attribs.push("world1");
  78793. attribs.push("world2");
  78794. attribs.push("world3");
  78795. }
  78796. // Get correct effect
  78797. var join = defines.join("\n");
  78798. if (this._cachedDefines !== join) {
  78799. this._cachedDefines = join;
  78800. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  78801. }
  78802. return this._glowMapGenerationEffect.isReady();
  78803. };
  78804. /**
  78805. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  78806. */
  78807. HighlightLayer.prototype.render = function () {
  78808. var currentEffect = this._glowMapMergeEffect;
  78809. // Check
  78810. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  78811. return;
  78812. var engine = this._scene.getEngine();
  78813. this.onBeforeComposeObservable.notifyObservers(this);
  78814. // Render
  78815. engine.enableEffect(currentEffect);
  78816. engine.setState(false);
  78817. // Cache
  78818. var previousStencilBuffer = engine.getStencilBuffer();
  78819. var previousStencilFunction = engine.getStencilFunction();
  78820. var previousStencilMask = engine.getStencilMask();
  78821. var previousStencilOperationPass = engine.getStencilOperationPass();
  78822. var previousStencilOperationFail = engine.getStencilOperationFail();
  78823. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  78824. var previousAlphaMode = engine.getAlphaMode();
  78825. // Texture
  78826. currentEffect.setTexture("textureSampler", this._blurTexture);
  78827. // VBOs
  78828. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78829. // Stencil operations
  78830. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  78831. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  78832. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  78833. // Draw order
  78834. engine.setAlphaMode(this._options.alphaBlendingMode);
  78835. engine.setStencilMask(0x00);
  78836. engine.setStencilBuffer(true);
  78837. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  78838. if (this.outerGlow) {
  78839. currentEffect.setFloat("offset", 0);
  78840. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  78841. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78842. }
  78843. if (this.innerGlow) {
  78844. currentEffect.setFloat("offset", 1);
  78845. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  78846. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78847. }
  78848. // Restore Cache
  78849. engine.setStencilFunction(previousStencilFunction);
  78850. engine.setStencilMask(previousStencilMask);
  78851. engine.setAlphaMode(previousAlphaMode);
  78852. engine.setStencilBuffer(previousStencilBuffer);
  78853. engine.setStencilOperationPass(previousStencilOperationPass);
  78854. engine.setStencilOperationFail(previousStencilOperationFail);
  78855. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  78856. engine._stencilState.reset();
  78857. this.onAfterComposeObservable.notifyObservers(this);
  78858. // Handle size changes.
  78859. var size = this._mainTexture.getSize();
  78860. this.setMainTextureSize();
  78861. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  78862. // Recreate RTT and post processes on size change.
  78863. this.onSizeChangedObservable.notifyObservers(this);
  78864. this.disposeTextureAndPostProcesses();
  78865. this.createTextureAndPostProcesses();
  78866. }
  78867. };
  78868. /**
  78869. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  78870. * @param mesh The mesh to exclude from the highlight layer
  78871. */
  78872. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  78873. if (!this._excludedMeshes) {
  78874. return;
  78875. }
  78876. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  78877. if (!meshExcluded) {
  78878. this._excludedMeshes[mesh.uniqueId] = {
  78879. mesh: mesh,
  78880. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  78881. mesh.getEngine().setStencilBuffer(false);
  78882. }),
  78883. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  78884. mesh.getEngine().setStencilBuffer(true);
  78885. }),
  78886. };
  78887. }
  78888. };
  78889. /**
  78890. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  78891. * @param mesh The mesh to highlight
  78892. */
  78893. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  78894. if (!this._excludedMeshes) {
  78895. return;
  78896. }
  78897. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  78898. if (meshExcluded) {
  78899. if (meshExcluded.beforeRender) {
  78900. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  78901. }
  78902. if (meshExcluded.afterRender) {
  78903. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  78904. }
  78905. }
  78906. this._excludedMeshes[mesh.uniqueId] = null;
  78907. };
  78908. /**
  78909. * Determine if a given mesh will be highlighted by the current HighlightLayer
  78910. * @param mesh mesh to test
  78911. * @returns true if the mesh will be highlighted by the current HighlightLayer
  78912. */
  78913. HighlightLayer.prototype.hasMesh = function (mesh) {
  78914. if (!this._meshes) {
  78915. return false;
  78916. }
  78917. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  78918. };
  78919. /**
  78920. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  78921. * @param mesh The mesh to highlight
  78922. * @param color The color of the highlight
  78923. * @param glowEmissiveOnly Extract the glow from the emissive texture
  78924. */
  78925. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  78926. var _this = this;
  78927. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  78928. if (!this._meshes) {
  78929. return;
  78930. }
  78931. var meshHighlight = this._meshes[mesh.uniqueId];
  78932. if (meshHighlight) {
  78933. meshHighlight.color = color;
  78934. }
  78935. else {
  78936. this._meshes[mesh.uniqueId] = {
  78937. mesh: mesh,
  78938. color: color,
  78939. // Lambda required for capture due to Observable this context
  78940. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  78941. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  78942. _this.defaultStencilReference(mesh);
  78943. }
  78944. else {
  78945. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  78946. }
  78947. }),
  78948. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  78949. glowEmissiveOnly: glowEmissiveOnly
  78950. };
  78951. }
  78952. this._shouldRender = true;
  78953. };
  78954. /**
  78955. * Remove a mesh from the highlight layer in order to make it stop glowing.
  78956. * @param mesh The mesh to highlight
  78957. */
  78958. HighlightLayer.prototype.removeMesh = function (mesh) {
  78959. if (!this._meshes) {
  78960. return;
  78961. }
  78962. var meshHighlight = this._meshes[mesh.uniqueId];
  78963. if (meshHighlight) {
  78964. if (meshHighlight.observerHighlight) {
  78965. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  78966. }
  78967. if (meshHighlight.observerDefault) {
  78968. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  78969. }
  78970. delete this._meshes[mesh.uniqueId];
  78971. }
  78972. this._shouldRender = false;
  78973. for (var meshHighlightToCheck in this._meshes) {
  78974. if (this._meshes[meshHighlightToCheck]) {
  78975. this._shouldRender = true;
  78976. break;
  78977. }
  78978. }
  78979. };
  78980. /**
  78981. * Returns true if the layer contains information to display, otherwise false.
  78982. */
  78983. HighlightLayer.prototype.shouldRender = function () {
  78984. return this.isEnabled && this._shouldRender;
  78985. };
  78986. /**
  78987. * Sets the main texture desired size which is the closest power of two
  78988. * of the engine canvas size.
  78989. */
  78990. HighlightLayer.prototype.setMainTextureSize = function () {
  78991. if (this._options.mainTextureFixedSize) {
  78992. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  78993. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  78994. }
  78995. else {
  78996. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  78997. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  78998. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  78999. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79000. }
  79001. };
  79002. /**
  79003. * Force the stencil to the normal expected value for none glowing parts
  79004. */
  79005. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79006. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79007. };
  79008. /**
  79009. * Dispose only the render target textures and post process.
  79010. */
  79011. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79012. this._blurTexture.dispose();
  79013. this._mainTexture.dispose();
  79014. this._downSamplePostprocess.dispose();
  79015. this._horizontalBlurPostprocess.dispose();
  79016. this._verticalBlurPostprocess.dispose();
  79017. };
  79018. /**
  79019. * Dispose the highlight layer and free resources.
  79020. */
  79021. HighlightLayer.prototype.dispose = function () {
  79022. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79023. if (vertexBuffer) {
  79024. vertexBuffer.dispose();
  79025. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79026. }
  79027. if (this._indexBuffer) {
  79028. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79029. this._indexBuffer = null;
  79030. }
  79031. // Clean textures and post processes
  79032. this.disposeTextureAndPostProcesses();
  79033. if (this._meshes) {
  79034. // Clean mesh references
  79035. for (var id in this._meshes) {
  79036. var meshHighlight = this._meshes[id];
  79037. if (meshHighlight && meshHighlight.mesh) {
  79038. if (meshHighlight.observerHighlight) {
  79039. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79040. }
  79041. if (meshHighlight.observerDefault) {
  79042. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79043. }
  79044. }
  79045. }
  79046. this._meshes = null;
  79047. }
  79048. if (this._excludedMeshes) {
  79049. for (var id in this._excludedMeshes) {
  79050. var meshHighlight = this._excludedMeshes[id];
  79051. if (meshHighlight) {
  79052. if (meshHighlight.beforeRender) {
  79053. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  79054. }
  79055. if (meshHighlight.afterRender) {
  79056. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  79057. }
  79058. }
  79059. }
  79060. this._excludedMeshes = null;
  79061. }
  79062. // Remove from scene
  79063. var index = this._scene.highlightLayers.indexOf(this, 0);
  79064. if (index > -1) {
  79065. this._scene.highlightLayers.splice(index, 1);
  79066. }
  79067. // Callback
  79068. this.onDisposeObservable.notifyObservers(this);
  79069. this.onDisposeObservable.clear();
  79070. this.onBeforeRenderMainTextureObservable.clear();
  79071. this.onBeforeBlurObservable.clear();
  79072. this.onBeforeComposeObservable.clear();
  79073. this.onAfterComposeObservable.clear();
  79074. this.onSizeChangedObservable.clear();
  79075. };
  79076. /**
  79077. * The neutral color used during the preparation of the glow effect.
  79078. * This is black by default as the blend operation is a blend operation.
  79079. */
  79080. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  79081. /**
  79082. * Stencil value used for glowing meshes.
  79083. */
  79084. HighlightLayer.glowingMeshStencilReference = 0x02;
  79085. /**
  79086. * Stencil value used for the other meshes in the scene.
  79087. */
  79088. HighlightLayer.normalMeshStencilReference = 0x01;
  79089. return HighlightLayer;
  79090. }());
  79091. BABYLON.HighlightLayer = HighlightLayer;
  79092. })(BABYLON || (BABYLON = {}));
  79093. //# sourceMappingURL=babylon.highlightlayer.js.map
  79094. var BABYLON;
  79095. (function (BABYLON) {
  79096. /**
  79097. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  79098. */
  79099. var AssetTaskState;
  79100. (function (AssetTaskState) {
  79101. /**
  79102. * Initialization
  79103. */
  79104. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  79105. /**
  79106. * Running
  79107. */
  79108. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  79109. /**
  79110. * Done
  79111. */
  79112. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  79113. /**
  79114. * Error
  79115. */
  79116. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  79117. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  79118. /**
  79119. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  79120. */
  79121. var AbstractAssetTask = /** @class */ (function () {
  79122. /**
  79123. * Creates a new {BABYLON.AssetsManager}
  79124. * @param name defines the name of the task
  79125. */
  79126. function AbstractAssetTask(
  79127. /**
  79128. * Task name
  79129. */ name) {
  79130. this.name = name;
  79131. this._isCompleted = false;
  79132. this._taskState = AssetTaskState.INIT;
  79133. }
  79134. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  79135. /**
  79136. * Get if the task is completed
  79137. */
  79138. get: function () {
  79139. return this._isCompleted;
  79140. },
  79141. enumerable: true,
  79142. configurable: true
  79143. });
  79144. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  79145. /**
  79146. * Gets the current state of the task
  79147. */
  79148. get: function () {
  79149. return this._taskState;
  79150. },
  79151. enumerable: true,
  79152. configurable: true
  79153. });
  79154. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  79155. /**
  79156. * Gets the current error object (if task is in error)
  79157. */
  79158. get: function () {
  79159. return this._errorObject;
  79160. },
  79161. enumerable: true,
  79162. configurable: true
  79163. });
  79164. /**
  79165. * Internal only
  79166. * @ignore
  79167. */
  79168. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  79169. if (this._errorObject) {
  79170. return;
  79171. }
  79172. this._errorObject = {
  79173. message: message,
  79174. exception: exception
  79175. };
  79176. };
  79177. /**
  79178. * Execute the current task
  79179. * @param scene defines the scene where you want your assets to be loaded
  79180. * @param onSuccess is a callback called when the task is successfully executed
  79181. * @param onError is a callback called if an error occurs
  79182. */
  79183. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79184. var _this = this;
  79185. this._taskState = AssetTaskState.RUNNING;
  79186. this.runTask(scene, function () {
  79187. _this.onDoneCallback(onSuccess, onError);
  79188. }, function (msg, exception) {
  79189. _this.onErrorCallback(onError, msg, exception);
  79190. });
  79191. };
  79192. /**
  79193. * Execute the current task
  79194. * @param scene defines the scene where you want your assets to be loaded
  79195. * @param onSuccess is a callback called when the task is successfully executed
  79196. * @param onError is a callback called if an error occurs
  79197. */
  79198. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79199. throw new Error("runTask is not implemented");
  79200. };
  79201. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  79202. this._taskState = AssetTaskState.ERROR;
  79203. this._errorObject = {
  79204. message: message,
  79205. exception: exception
  79206. };
  79207. if (this.onError) {
  79208. this.onError(this, message, exception);
  79209. }
  79210. onError();
  79211. };
  79212. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  79213. try {
  79214. this._taskState = AssetTaskState.DONE;
  79215. this._isCompleted = true;
  79216. if (this.onSuccess) {
  79217. this.onSuccess(this);
  79218. }
  79219. onSuccess();
  79220. }
  79221. catch (e) {
  79222. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  79223. }
  79224. };
  79225. return AbstractAssetTask;
  79226. }());
  79227. BABYLON.AbstractAssetTask = AbstractAssetTask;
  79228. /**
  79229. * Class used to share progress information about assets loading
  79230. */
  79231. var AssetsProgressEvent = /** @class */ (function () {
  79232. /**
  79233. * Creates a {BABYLON.AssetsProgressEvent}
  79234. * @param remainingCount defines the number of remaining tasks to process
  79235. * @param totalCount defines the total number of tasks
  79236. * @param task defines the task that was just processed
  79237. */
  79238. function AssetsProgressEvent(remainingCount, totalCount, task) {
  79239. this.remainingCount = remainingCount;
  79240. this.totalCount = totalCount;
  79241. this.task = task;
  79242. }
  79243. return AssetsProgressEvent;
  79244. }());
  79245. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  79246. /**
  79247. * Define a task used by {BABYLON.AssetsManager} to load meshes
  79248. */
  79249. var MeshAssetTask = /** @class */ (function (_super) {
  79250. __extends(MeshAssetTask, _super);
  79251. /**
  79252. * Creates a new {BABYLON.MeshAssetTask}
  79253. * @param name defines the name of the task
  79254. * @param meshesNames defines the list of mesh's names you want to load
  79255. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  79256. * @param sceneFilename defines the filename of the scene to load from
  79257. */
  79258. function MeshAssetTask(
  79259. /**
  79260. * Defines the name of the task
  79261. */
  79262. name,
  79263. /**
  79264. * Defines the list of mesh's names you want to load
  79265. */
  79266. meshesNames,
  79267. /**
  79268. * Defines the root url to use as a base to load your meshes and associated resources
  79269. */
  79270. rootUrl,
  79271. /**
  79272. * Defines the filename of the scene to load from
  79273. */
  79274. sceneFilename) {
  79275. var _this = _super.call(this, name) || this;
  79276. _this.name = name;
  79277. _this.meshesNames = meshesNames;
  79278. _this.rootUrl = rootUrl;
  79279. _this.sceneFilename = sceneFilename;
  79280. return _this;
  79281. }
  79282. /**
  79283. * Execute the current task
  79284. * @param scene defines the scene where you want your assets to be loaded
  79285. * @param onSuccess is a callback called when the task is successfully executed
  79286. * @param onError is a callback called if an error occurs
  79287. */
  79288. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79289. var _this = this;
  79290. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  79291. _this.loadedMeshes = meshes;
  79292. _this.loadedParticleSystems = particleSystems;
  79293. _this.loadedSkeletons = skeletons;
  79294. onSuccess();
  79295. }, null, function (scene, message, exception) {
  79296. onError(message, exception);
  79297. });
  79298. };
  79299. return MeshAssetTask;
  79300. }(AbstractAssetTask));
  79301. BABYLON.MeshAssetTask = MeshAssetTask;
  79302. /**
  79303. * Define a task used by {BABYLON.AssetsManager} to load text content
  79304. */
  79305. var TextFileAssetTask = /** @class */ (function (_super) {
  79306. __extends(TextFileAssetTask, _super);
  79307. /**
  79308. * Creates a new TextFileAssetTask object
  79309. * @param name defines the name of the task
  79310. * @param url defines the location of the file to load
  79311. */
  79312. function TextFileAssetTask(
  79313. /**
  79314. * Defines the name of the task
  79315. */
  79316. name,
  79317. /**
  79318. * Defines the location of the file to load
  79319. */
  79320. url) {
  79321. var _this = _super.call(this, name) || this;
  79322. _this.name = name;
  79323. _this.url = url;
  79324. return _this;
  79325. }
  79326. /**
  79327. * Execute the current task
  79328. * @param scene defines the scene where you want your assets to be loaded
  79329. * @param onSuccess is a callback called when the task is successfully executed
  79330. * @param onError is a callback called if an error occurs
  79331. */
  79332. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79333. var _this = this;
  79334. scene._loadFile(this.url, function (data) {
  79335. _this.text = data;
  79336. onSuccess();
  79337. }, undefined, false, true, function (request, exception) {
  79338. if (request) {
  79339. onError(request.status + " " + request.statusText, exception);
  79340. }
  79341. });
  79342. };
  79343. return TextFileAssetTask;
  79344. }(AbstractAssetTask));
  79345. BABYLON.TextFileAssetTask = TextFileAssetTask;
  79346. /**
  79347. * Define a task used by {BABYLON.AssetsManager} to load binary data
  79348. */
  79349. var BinaryFileAssetTask = /** @class */ (function (_super) {
  79350. __extends(BinaryFileAssetTask, _super);
  79351. /**
  79352. * Creates a new BinaryFileAssetTask object
  79353. * @param name defines the name of the new task
  79354. * @param url defines the location of the file to load
  79355. */
  79356. function BinaryFileAssetTask(
  79357. /**
  79358. * Defines the name of the task
  79359. */
  79360. name,
  79361. /**
  79362. * Defines the location of the file to load
  79363. */
  79364. url) {
  79365. var _this = _super.call(this, name) || this;
  79366. _this.name = name;
  79367. _this.url = url;
  79368. return _this;
  79369. }
  79370. /**
  79371. * Execute the current task
  79372. * @param scene defines the scene where you want your assets to be loaded
  79373. * @param onSuccess is a callback called when the task is successfully executed
  79374. * @param onError is a callback called if an error occurs
  79375. */
  79376. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79377. var _this = this;
  79378. scene._loadFile(this.url, function (data) {
  79379. _this.data = data;
  79380. onSuccess();
  79381. }, undefined, true, true, function (request, exception) {
  79382. if (request) {
  79383. onError(request.status + " " + request.statusText, exception);
  79384. }
  79385. });
  79386. };
  79387. return BinaryFileAssetTask;
  79388. }(AbstractAssetTask));
  79389. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  79390. /**
  79391. * Define a task used by {BABYLON.AssetsManager} to load images
  79392. */
  79393. var ImageAssetTask = /** @class */ (function (_super) {
  79394. __extends(ImageAssetTask, _super);
  79395. /**
  79396. * Creates a new ImageAssetTask
  79397. * @param name defines the name of the task
  79398. * @param url defines the location of the image to load
  79399. */
  79400. function ImageAssetTask(
  79401. /**
  79402. * Defines the name of the task
  79403. */
  79404. name,
  79405. /**
  79406. * Defines the location of the image to load
  79407. */
  79408. url) {
  79409. var _this = _super.call(this, name) || this;
  79410. _this.name = name;
  79411. _this.url = url;
  79412. return _this;
  79413. }
  79414. /**
  79415. * Execute the current task
  79416. * @param scene defines the scene where you want your assets to be loaded
  79417. * @param onSuccess is a callback called when the task is successfully executed
  79418. * @param onError is a callback called if an error occurs
  79419. */
  79420. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79421. var _this = this;
  79422. var img = new Image();
  79423. BABYLON.Tools.SetCorsBehavior(this.url, img);
  79424. img.onload = function () {
  79425. _this.image = img;
  79426. onSuccess();
  79427. };
  79428. img.onerror = function (err) {
  79429. onError("Error loading image", err);
  79430. };
  79431. img.src = this.url;
  79432. };
  79433. return ImageAssetTask;
  79434. }(AbstractAssetTask));
  79435. BABYLON.ImageAssetTask = ImageAssetTask;
  79436. /**
  79437. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  79438. */
  79439. var TextureAssetTask = /** @class */ (function (_super) {
  79440. __extends(TextureAssetTask, _super);
  79441. /**
  79442. * Creates a new TextureAssetTask object
  79443. * @param name defines the name of the task
  79444. * @param url defines the location of the file to load
  79445. * @param noMipmap defines if mipmap should not be generated (default is false)
  79446. * @param invertY defines if texture must be inverted on Y axis (default is false)
  79447. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79448. */
  79449. function TextureAssetTask(
  79450. /**
  79451. * Defines the name of the task
  79452. */
  79453. name,
  79454. /**
  79455. * Defines the location of the file to load
  79456. */
  79457. url,
  79458. /**
  79459. * Defines if mipmap should not be generated (default is false)
  79460. */
  79461. noMipmap,
  79462. /**
  79463. * Defines if texture must be inverted on Y axis (default is false)
  79464. */
  79465. invertY,
  79466. /**
  79467. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  79468. */
  79469. samplingMode) {
  79470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79471. var _this = _super.call(this, name) || this;
  79472. _this.name = name;
  79473. _this.url = url;
  79474. _this.noMipmap = noMipmap;
  79475. _this.invertY = invertY;
  79476. _this.samplingMode = samplingMode;
  79477. return _this;
  79478. }
  79479. /**
  79480. * Execute the current task
  79481. * @param scene defines the scene where you want your assets to be loaded
  79482. * @param onSuccess is a callback called when the task is successfully executed
  79483. * @param onError is a callback called if an error occurs
  79484. */
  79485. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79486. var onload = function () {
  79487. onSuccess();
  79488. };
  79489. var onerror = function (message, exception) {
  79490. onError(message, exception);
  79491. };
  79492. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  79493. };
  79494. return TextureAssetTask;
  79495. }(AbstractAssetTask));
  79496. BABYLON.TextureAssetTask = TextureAssetTask;
  79497. /**
  79498. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  79499. */
  79500. var CubeTextureAssetTask = /** @class */ (function (_super) {
  79501. __extends(CubeTextureAssetTask, _super);
  79502. /**
  79503. * Creates a new CubeTextureAssetTask
  79504. * @param name defines the name of the task
  79505. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79506. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79507. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79508. * @param files defines the explicit list of files (undefined by default)
  79509. */
  79510. function CubeTextureAssetTask(
  79511. /**
  79512. * Defines the name of the task
  79513. */
  79514. name,
  79515. /**
  79516. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  79517. */
  79518. url,
  79519. /**
  79520. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  79521. */
  79522. extensions,
  79523. /**
  79524. * Defines if mipmaps should not be generated (default is false)
  79525. */
  79526. noMipmap,
  79527. /**
  79528. * Defines the explicit list of files (undefined by default)
  79529. */
  79530. files) {
  79531. var _this = _super.call(this, name) || this;
  79532. _this.name = name;
  79533. _this.url = url;
  79534. _this.extensions = extensions;
  79535. _this.noMipmap = noMipmap;
  79536. _this.files = files;
  79537. return _this;
  79538. }
  79539. /**
  79540. * Execute the current task
  79541. * @param scene defines the scene where you want your assets to be loaded
  79542. * @param onSuccess is a callback called when the task is successfully executed
  79543. * @param onError is a callback called if an error occurs
  79544. */
  79545. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79546. var onload = function () {
  79547. onSuccess();
  79548. };
  79549. var onerror = function (message, exception) {
  79550. onError(message, exception);
  79551. };
  79552. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  79553. };
  79554. return CubeTextureAssetTask;
  79555. }(AbstractAssetTask));
  79556. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  79557. /**
  79558. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  79559. */
  79560. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  79561. __extends(HDRCubeTextureAssetTask, _super);
  79562. /**
  79563. * Creates a new HDRCubeTextureAssetTask object
  79564. * @param name defines the name of the task
  79565. * @param url defines the location of the file to load
  79566. * @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.
  79567. * @param noMipmap defines if mipmaps should not be generated (default is false)
  79568. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79569. * @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)
  79570. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79571. */
  79572. function HDRCubeTextureAssetTask(
  79573. /**
  79574. * Defines the name of the task
  79575. */
  79576. name,
  79577. /**
  79578. * Defines the location of the file to load
  79579. */
  79580. url,
  79581. /**
  79582. * 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.
  79583. */
  79584. size,
  79585. /**
  79586. * Defines if mipmaps should not be generated (default is false)
  79587. */
  79588. noMipmap,
  79589. /**
  79590. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  79591. */
  79592. generateHarmonics,
  79593. /**
  79594. * 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)
  79595. */
  79596. useInGammaSpace,
  79597. /**
  79598. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  79599. */
  79600. usePMREMGenerator) {
  79601. if (noMipmap === void 0) { noMipmap = false; }
  79602. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79603. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79604. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79605. var _this = _super.call(this, name) || this;
  79606. _this.name = name;
  79607. _this.url = url;
  79608. _this.size = size;
  79609. _this.noMipmap = noMipmap;
  79610. _this.generateHarmonics = generateHarmonics;
  79611. _this.useInGammaSpace = useInGammaSpace;
  79612. _this.usePMREMGenerator = usePMREMGenerator;
  79613. return _this;
  79614. }
  79615. /**
  79616. * Execute the current task
  79617. * @param scene defines the scene where you want your assets to be loaded
  79618. * @param onSuccess is a callback called when the task is successfully executed
  79619. * @param onError is a callback called if an error occurs
  79620. */
  79621. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79622. var onload = function () {
  79623. onSuccess();
  79624. };
  79625. var onerror = function (message, exception) {
  79626. onError(message, exception);
  79627. };
  79628. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  79629. };
  79630. return HDRCubeTextureAssetTask;
  79631. }(AbstractAssetTask));
  79632. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  79633. /**
  79634. * This class can be used to easily import assets into a scene
  79635. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  79636. */
  79637. var AssetsManager = /** @class */ (function () {
  79638. /**
  79639. * Creates a new AssetsManager
  79640. * @param scene defines the scene to work on
  79641. */
  79642. function AssetsManager(scene) {
  79643. this._isLoading = false;
  79644. this._tasks = new Array();
  79645. this._waitingTasksCount = 0;
  79646. this._totalTasksCount = 0;
  79647. /**
  79648. * Observable called when all tasks are processed
  79649. */
  79650. this.onTaskSuccessObservable = new BABYLON.Observable();
  79651. /**
  79652. * Observable called when a task had an error
  79653. */
  79654. this.onTaskErrorObservable = new BABYLON.Observable();
  79655. /**
  79656. * Observable called when a task is successful
  79657. */
  79658. this.onTasksDoneObservable = new BABYLON.Observable();
  79659. /**
  79660. * Observable called when a task is done (whatever the result is)
  79661. */
  79662. this.onProgressObservable = new BABYLON.Observable();
  79663. /**
  79664. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  79665. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  79666. */
  79667. this.useDefaultLoadingScreen = true;
  79668. this._scene = scene;
  79669. }
  79670. /**
  79671. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  79672. * @param taskName defines the name of the new task
  79673. * @param meshesNames defines the name of meshes to load
  79674. * @param rootUrl defines the root url to use to locate files
  79675. * @param sceneFilename defines the filename of the scene file
  79676. * @returns a new {BABYLON.MeshAssetTask} object
  79677. */
  79678. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  79679. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  79680. this._tasks.push(task);
  79681. return task;
  79682. };
  79683. /**
  79684. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  79685. * @param taskName defines the name of the new task
  79686. * @param url defines the url of the file to load
  79687. * @returns a new {BABYLON.TextFileAssetTask} object
  79688. */
  79689. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  79690. var task = new TextFileAssetTask(taskName, url);
  79691. this._tasks.push(task);
  79692. return task;
  79693. };
  79694. /**
  79695. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  79696. * @param taskName defines the name of the new task
  79697. * @param url defines the url of the file to load
  79698. * @returns a new {BABYLON.BinaryFileAssetTask} object
  79699. */
  79700. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  79701. var task = new BinaryFileAssetTask(taskName, url);
  79702. this._tasks.push(task);
  79703. return task;
  79704. };
  79705. /**
  79706. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  79707. * @param taskName defines the name of the new task
  79708. * @param url defines the url of the file to load
  79709. * @returns a new {BABYLON.ImageAssetTask} object
  79710. */
  79711. AssetsManager.prototype.addImageTask = function (taskName, url) {
  79712. var task = new ImageAssetTask(taskName, url);
  79713. this._tasks.push(task);
  79714. return task;
  79715. };
  79716. /**
  79717. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  79718. * @param taskName defines the name of the new task
  79719. * @param url defines the url of the file to load
  79720. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  79721. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  79722. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  79723. * @returns a new {BABYLON.TextureAssetTask} object
  79724. */
  79725. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  79726. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  79727. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  79728. this._tasks.push(task);
  79729. return task;
  79730. };
  79731. /**
  79732. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  79733. * @param taskName defines the name of the new task
  79734. * @param url defines the url of the file to load
  79735. * @param extensions defines the extension to use to load the cube map (can be null)
  79736. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  79737. * @param files defines the list of files to load (can be null)
  79738. * @returns a new {BABYLON.CubeTextureAssetTask} object
  79739. */
  79740. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  79741. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  79742. this._tasks.push(task);
  79743. return task;
  79744. };
  79745. /**
  79746. *
  79747. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  79748. * @param taskName defines the name of the new task
  79749. * @param url defines the url of the file to load
  79750. * @param size defines the size you want for the cubemap (can be null)
  79751. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  79752. * @param generateHarmonics defines if you want to automatically generate (true by default)
  79753. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  79754. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  79755. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  79756. */
  79757. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  79758. if (noMipmap === void 0) { noMipmap = false; }
  79759. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79760. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79761. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79762. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  79763. this._tasks.push(task);
  79764. return task;
  79765. };
  79766. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  79767. var _this = this;
  79768. this._waitingTasksCount--;
  79769. try {
  79770. if (task.taskState === AssetTaskState.DONE) {
  79771. // Let's remove successfull tasks
  79772. BABYLON.Tools.SetImmediate(function () {
  79773. var index = _this._tasks.indexOf(task);
  79774. if (index > -1) {
  79775. _this._tasks.splice(index, 1);
  79776. }
  79777. });
  79778. }
  79779. if (this.onProgress) {
  79780. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  79781. }
  79782. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  79783. }
  79784. catch (e) {
  79785. BABYLON.Tools.Error("Error running progress callbacks.");
  79786. console.log(e);
  79787. }
  79788. if (this._waitingTasksCount === 0) {
  79789. try {
  79790. if (this.onFinish) {
  79791. this.onFinish(this._tasks);
  79792. }
  79793. this.onTasksDoneObservable.notifyObservers(this._tasks);
  79794. }
  79795. catch (e) {
  79796. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  79797. console.log(e);
  79798. }
  79799. this._isLoading = false;
  79800. this._scene.getEngine().hideLoadingUI();
  79801. }
  79802. };
  79803. AssetsManager.prototype._runTask = function (task) {
  79804. var _this = this;
  79805. var done = function () {
  79806. try {
  79807. if (_this.onTaskSuccess) {
  79808. _this.onTaskSuccess(task);
  79809. }
  79810. _this.onTaskSuccessObservable.notifyObservers(task);
  79811. _this._decreaseWaitingTasksCount(task);
  79812. }
  79813. catch (e) {
  79814. error("Error executing task success callbacks", e);
  79815. }
  79816. };
  79817. var error = function (message, exception) {
  79818. task._setErrorObject(message, exception);
  79819. if (_this.onTaskError) {
  79820. _this.onTaskError(task);
  79821. }
  79822. _this.onTaskErrorObservable.notifyObservers(task);
  79823. _this._decreaseWaitingTasksCount(task);
  79824. };
  79825. task.run(this._scene, done, error);
  79826. };
  79827. /**
  79828. * Reset the {BABYLON.AssetsManager} and remove all tasks
  79829. * @return the current instance of the {BABYLON.AssetsManager}
  79830. */
  79831. AssetsManager.prototype.reset = function () {
  79832. this._isLoading = false;
  79833. this._tasks = new Array();
  79834. return this;
  79835. };
  79836. /**
  79837. * Start the loading process
  79838. * @return the current instance of the {BABYLON.AssetsManager}
  79839. */
  79840. AssetsManager.prototype.load = function () {
  79841. if (this._isLoading) {
  79842. return this;
  79843. }
  79844. this._isLoading = true;
  79845. this._waitingTasksCount = this._tasks.length;
  79846. this._totalTasksCount = this._tasks.length;
  79847. if (this._waitingTasksCount === 0) {
  79848. if (this.onFinish) {
  79849. this.onFinish(this._tasks);
  79850. }
  79851. this.onTasksDoneObservable.notifyObservers(this._tasks);
  79852. return this;
  79853. }
  79854. if (this.useDefaultLoadingScreen) {
  79855. this._scene.getEngine().displayLoadingUI();
  79856. }
  79857. for (var index = 0; index < this._tasks.length; index++) {
  79858. var task = this._tasks[index];
  79859. this._runTask(task);
  79860. }
  79861. return this;
  79862. };
  79863. return AssetsManager;
  79864. }());
  79865. BABYLON.AssetsManager = AssetsManager;
  79866. })(BABYLON || (BABYLON = {}));
  79867. //# sourceMappingURL=babylon.assetsManager.js.map
  79868. var BABYLON;
  79869. (function (BABYLON) {
  79870. var serializedGeometries = [];
  79871. var serializeGeometry = function (geometry, serializationGeometries) {
  79872. if (serializedGeometries[geometry.id]) {
  79873. return;
  79874. }
  79875. if (geometry.doNotSerialize) {
  79876. return;
  79877. }
  79878. if (geometry instanceof BABYLON.BoxGeometry) {
  79879. serializationGeometries.boxes.push(geometry.serialize());
  79880. }
  79881. else if (geometry instanceof BABYLON.SphereGeometry) {
  79882. serializationGeometries.spheres.push(geometry.serialize());
  79883. }
  79884. else if (geometry instanceof BABYLON.CylinderGeometry) {
  79885. serializationGeometries.cylinders.push(geometry.serialize());
  79886. }
  79887. else if (geometry instanceof BABYLON.TorusGeometry) {
  79888. serializationGeometries.toruses.push(geometry.serialize());
  79889. }
  79890. else if (geometry instanceof BABYLON.GroundGeometry) {
  79891. serializationGeometries.grounds.push(geometry.serialize());
  79892. }
  79893. else if (geometry instanceof BABYLON.Plane) {
  79894. serializationGeometries.planes.push(geometry.serialize());
  79895. }
  79896. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  79897. serializationGeometries.torusKnots.push(geometry.serialize());
  79898. }
  79899. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  79900. throw new Error("Unknown primitive type");
  79901. }
  79902. else {
  79903. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  79904. }
  79905. serializedGeometries[geometry.id] = true;
  79906. };
  79907. var serializeMesh = function (mesh, serializationScene) {
  79908. var serializationObject = {};
  79909. // Geometry
  79910. var geometry = mesh._geometry;
  79911. if (geometry) {
  79912. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  79913. // 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
  79914. serializeGeometry(geometry, serializationScene.geometries);
  79915. }
  79916. }
  79917. // Custom
  79918. if (mesh.serialize) {
  79919. mesh.serialize(serializationObject);
  79920. }
  79921. return serializationObject;
  79922. };
  79923. var finalizeSingleMesh = function (mesh, serializationObject) {
  79924. //only works if the mesh is already loaded
  79925. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  79926. //serialize material
  79927. if (mesh.material) {
  79928. if (mesh.material instanceof BABYLON.StandardMaterial) {
  79929. serializationObject.materials = serializationObject.materials || [];
  79930. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  79931. serializationObject.materials.push(mesh.material.serialize());
  79932. }
  79933. }
  79934. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  79935. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  79936. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  79937. serializationObject.multiMaterials.push(mesh.material.serialize());
  79938. }
  79939. }
  79940. }
  79941. //serialize geometry
  79942. var geometry = mesh._geometry;
  79943. if (geometry) {
  79944. if (!serializationObject.geometries) {
  79945. serializationObject.geometries = {};
  79946. serializationObject.geometries.boxes = [];
  79947. serializationObject.geometries.spheres = [];
  79948. serializationObject.geometries.cylinders = [];
  79949. serializationObject.geometries.toruses = [];
  79950. serializationObject.geometries.grounds = [];
  79951. serializationObject.geometries.planes = [];
  79952. serializationObject.geometries.torusKnots = [];
  79953. serializationObject.geometries.vertexData = [];
  79954. }
  79955. serializeGeometry(geometry, serializationObject.geometries);
  79956. }
  79957. // Skeletons
  79958. if (mesh.skeleton) {
  79959. serializationObject.skeletons = serializationObject.skeletons || [];
  79960. serializationObject.skeletons.push(mesh.skeleton.serialize());
  79961. }
  79962. //serialize the actual mesh
  79963. serializationObject.meshes = serializationObject.meshes || [];
  79964. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  79965. }
  79966. };
  79967. var SceneSerializer = /** @class */ (function () {
  79968. function SceneSerializer() {
  79969. }
  79970. SceneSerializer.ClearCache = function () {
  79971. serializedGeometries = [];
  79972. };
  79973. SceneSerializer.Serialize = function (scene) {
  79974. var serializationObject = {};
  79975. SceneSerializer.ClearCache();
  79976. // Scene
  79977. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  79978. serializationObject.autoClear = scene.autoClear;
  79979. serializationObject.clearColor = scene.clearColor.asArray();
  79980. serializationObject.ambientColor = scene.ambientColor.asArray();
  79981. serializationObject.gravity = scene.gravity.asArray();
  79982. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  79983. serializationObject.workerCollisions = scene.workerCollisions;
  79984. // Fog
  79985. if (scene.fogMode && scene.fogMode !== 0) {
  79986. serializationObject.fogMode = scene.fogMode;
  79987. serializationObject.fogColor = scene.fogColor.asArray();
  79988. serializationObject.fogStart = scene.fogStart;
  79989. serializationObject.fogEnd = scene.fogEnd;
  79990. serializationObject.fogDensity = scene.fogDensity;
  79991. }
  79992. //Physics
  79993. if (scene.isPhysicsEnabled()) {
  79994. var physicEngine = scene.getPhysicsEngine();
  79995. if (physicEngine) {
  79996. serializationObject.physicsEnabled = true;
  79997. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  79998. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  79999. }
  80000. }
  80001. // Metadata
  80002. if (scene.metadata) {
  80003. serializationObject.metadata = scene.metadata;
  80004. }
  80005. // Morph targets
  80006. serializationObject.morphTargetManagers = [];
  80007. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80008. var abstractMesh = _a[_i];
  80009. var manager = abstractMesh.morphTargetManager;
  80010. if (manager) {
  80011. serializationObject.morphTargetManagers.push(manager.serialize());
  80012. }
  80013. }
  80014. // Lights
  80015. serializationObject.lights = [];
  80016. var index;
  80017. var light;
  80018. for (index = 0; index < scene.lights.length; index++) {
  80019. light = scene.lights[index];
  80020. if (!light.doNotSerialize) {
  80021. serializationObject.lights.push(light.serialize());
  80022. }
  80023. }
  80024. // Cameras
  80025. serializationObject.cameras = [];
  80026. for (index = 0; index < scene.cameras.length; index++) {
  80027. var camera = scene.cameras[index];
  80028. if (!camera.doNotSerialize) {
  80029. serializationObject.cameras.push(camera.serialize());
  80030. }
  80031. }
  80032. if (scene.activeCamera) {
  80033. serializationObject.activeCameraID = scene.activeCamera.id;
  80034. }
  80035. // Animations
  80036. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80037. // Materials
  80038. serializationObject.materials = [];
  80039. serializationObject.multiMaterials = [];
  80040. var material;
  80041. for (index = 0; index < scene.materials.length; index++) {
  80042. material = scene.materials[index];
  80043. if (!material.doNotSerialize) {
  80044. serializationObject.materials.push(material.serialize());
  80045. }
  80046. }
  80047. // MultiMaterials
  80048. serializationObject.multiMaterials = [];
  80049. for (index = 0; index < scene.multiMaterials.length; index++) {
  80050. var multiMaterial = scene.multiMaterials[index];
  80051. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80052. }
  80053. // Environment texture
  80054. if (scene.environmentTexture) {
  80055. serializationObject.environmentTexture = scene.environmentTexture.name;
  80056. }
  80057. // Skeletons
  80058. serializationObject.skeletons = [];
  80059. for (index = 0; index < scene.skeletons.length; index++) {
  80060. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  80061. }
  80062. // Transform nodes
  80063. serializationObject.transformNodes = [];
  80064. for (index = 0; index < scene.transformNodes.length; index++) {
  80065. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  80066. }
  80067. // Geometries
  80068. serializationObject.geometries = {};
  80069. serializationObject.geometries.boxes = [];
  80070. serializationObject.geometries.spheres = [];
  80071. serializationObject.geometries.cylinders = [];
  80072. serializationObject.geometries.toruses = [];
  80073. serializationObject.geometries.grounds = [];
  80074. serializationObject.geometries.planes = [];
  80075. serializationObject.geometries.torusKnots = [];
  80076. serializationObject.geometries.vertexData = [];
  80077. serializedGeometries = [];
  80078. var geometries = scene.getGeometries();
  80079. for (index = 0; index < geometries.length; index++) {
  80080. var geometry = geometries[index];
  80081. if (geometry.isReady()) {
  80082. serializeGeometry(geometry, serializationObject.geometries);
  80083. }
  80084. }
  80085. // Meshes
  80086. serializationObject.meshes = [];
  80087. for (index = 0; index < scene.meshes.length; index++) {
  80088. var abstractMesh = scene.meshes[index];
  80089. if (abstractMesh instanceof BABYLON.Mesh) {
  80090. var mesh = abstractMesh;
  80091. if (!mesh.doNotSerialize) {
  80092. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80093. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80094. }
  80095. }
  80096. }
  80097. }
  80098. // Particles Systems
  80099. serializationObject.particleSystems = [];
  80100. for (index = 0; index < scene.particleSystems.length; index++) {
  80101. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  80102. }
  80103. // Lens flares
  80104. serializationObject.lensFlareSystems = [];
  80105. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  80106. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  80107. }
  80108. // Shadows
  80109. serializationObject.shadowGenerators = [];
  80110. for (index = 0; index < scene.lights.length; index++) {
  80111. light = scene.lights[index];
  80112. var shadowGenerator = light.getShadowGenerator();
  80113. if (shadowGenerator) {
  80114. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  80115. }
  80116. }
  80117. // Action Manager
  80118. if (scene.actionManager) {
  80119. serializationObject.actions = scene.actionManager.serialize("scene");
  80120. }
  80121. // Audio
  80122. serializationObject.sounds = [];
  80123. for (index = 0; index < scene.soundTracks.length; index++) {
  80124. var soundtrack = scene.soundTracks[index];
  80125. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  80126. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  80127. }
  80128. }
  80129. return serializationObject;
  80130. };
  80131. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  80132. if (withParents === void 0) { withParents = false; }
  80133. if (withChildren === void 0) { withChildren = false; }
  80134. var serializationObject = {};
  80135. SceneSerializer.ClearCache();
  80136. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  80137. if (withParents || withChildren) {
  80138. //deliberate for loop! not for each, appended should be processed as well.
  80139. for (var i = 0; i < toSerialize.length; ++i) {
  80140. if (withChildren) {
  80141. toSerialize[i].getDescendants().forEach(function (node) {
  80142. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  80143. toSerialize.push(node);
  80144. }
  80145. });
  80146. }
  80147. //make sure the array doesn't contain the object already
  80148. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  80149. toSerialize.push(toSerialize[i].parent);
  80150. }
  80151. }
  80152. }
  80153. toSerialize.forEach(function (mesh) {
  80154. finalizeSingleMesh(mesh, serializationObject);
  80155. });
  80156. return serializationObject;
  80157. };
  80158. return SceneSerializer;
  80159. }());
  80160. BABYLON.SceneSerializer = SceneSerializer;
  80161. })(BABYLON || (BABYLON = {}));
  80162. //# sourceMappingURL=babylon.sceneSerializer.js.map
  80163. var BABYLON;
  80164. (function (BABYLON) {
  80165. var ReflectionProbe = /** @class */ (function () {
  80166. function ReflectionProbe(name, size, scene, generateMipMaps) {
  80167. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80168. var _this = this;
  80169. this.name = name;
  80170. this._viewMatrix = BABYLON.Matrix.Identity();
  80171. this._target = BABYLON.Vector3.Zero();
  80172. this._add = BABYLON.Vector3.Zero();
  80173. this.invertYAxis = false;
  80174. this.position = BABYLON.Vector3.Zero();
  80175. this._scene = scene;
  80176. this._scene.reflectionProbes.push(this);
  80177. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  80178. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  80179. switch (faceIndex) {
  80180. case 0:
  80181. _this._add.copyFromFloats(1, 0, 0);
  80182. break;
  80183. case 1:
  80184. _this._add.copyFromFloats(-1, 0, 0);
  80185. break;
  80186. case 2:
  80187. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  80188. break;
  80189. case 3:
  80190. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  80191. break;
  80192. case 4:
  80193. _this._add.copyFromFloats(0, 0, 1);
  80194. break;
  80195. case 5:
  80196. _this._add.copyFromFloats(0, 0, -1);
  80197. break;
  80198. }
  80199. if (_this._attachedMesh) {
  80200. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  80201. }
  80202. _this.position.addToRef(_this._add, _this._target);
  80203. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  80204. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  80205. scene._forcedViewPosition = _this.position;
  80206. });
  80207. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  80208. scene._forcedViewPosition = null;
  80209. scene.updateTransformMatrix(true);
  80210. });
  80211. if (scene.activeCamera) {
  80212. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80213. }
  80214. }
  80215. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  80216. get: function () {
  80217. return this._renderTargetTexture.samples;
  80218. },
  80219. set: function (value) {
  80220. this._renderTargetTexture.samples = value;
  80221. },
  80222. enumerable: true,
  80223. configurable: true
  80224. });
  80225. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  80226. get: function () {
  80227. return this._renderTargetTexture.refreshRate;
  80228. },
  80229. set: function (value) {
  80230. this._renderTargetTexture.refreshRate = value;
  80231. },
  80232. enumerable: true,
  80233. configurable: true
  80234. });
  80235. ReflectionProbe.prototype.getScene = function () {
  80236. return this._scene;
  80237. };
  80238. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  80239. get: function () {
  80240. return this._renderTargetTexture;
  80241. },
  80242. enumerable: true,
  80243. configurable: true
  80244. });
  80245. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  80246. get: function () {
  80247. return this._renderTargetTexture.renderList;
  80248. },
  80249. enumerable: true,
  80250. configurable: true
  80251. });
  80252. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  80253. this._attachedMesh = mesh;
  80254. };
  80255. /**
  80256. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  80257. *
  80258. * @param renderingGroupId The rendering group id corresponding to its index
  80259. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  80260. */
  80261. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  80262. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  80263. };
  80264. ReflectionProbe.prototype.dispose = function () {
  80265. var index = this._scene.reflectionProbes.indexOf(this);
  80266. if (index !== -1) {
  80267. // Remove from the scene if found
  80268. this._scene.reflectionProbes.splice(index, 1);
  80269. }
  80270. if (this._renderTargetTexture) {
  80271. this._renderTargetTexture.dispose();
  80272. this._renderTargetTexture = null;
  80273. }
  80274. };
  80275. return ReflectionProbe;
  80276. }());
  80277. BABYLON.ReflectionProbe = ReflectionProbe;
  80278. })(BABYLON || (BABYLON = {}));
  80279. //# sourceMappingURL=babylon.reflectionProbe.js.map
  80280. var BABYLON;
  80281. (function (BABYLON) {
  80282. var Layer = /** @class */ (function () {
  80283. function Layer(name, imgUrl, scene, isBackground, color) {
  80284. this.name = name;
  80285. this.scale = new BABYLON.Vector2(1, 1);
  80286. this.offset = new BABYLON.Vector2(0, 0);
  80287. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  80288. this.layerMask = 0x0FFFFFFF;
  80289. this._vertexBuffers = {};
  80290. // Events
  80291. /**
  80292. * An event triggered when the layer is disposed.
  80293. * @type {BABYLON.Observable}
  80294. */
  80295. this.onDisposeObservable = new BABYLON.Observable();
  80296. /**
  80297. * An event triggered before rendering the scene
  80298. * @type {BABYLON.Observable}
  80299. */
  80300. this.onBeforeRenderObservable = new BABYLON.Observable();
  80301. /**
  80302. * An event triggered after rendering the scene
  80303. * @type {BABYLON.Observable}
  80304. */
  80305. this.onAfterRenderObservable = new BABYLON.Observable();
  80306. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  80307. this.isBackground = isBackground === undefined ? true : isBackground;
  80308. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  80309. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  80310. this._scene.layers.push(this);
  80311. var engine = this._scene.getEngine();
  80312. // VBO
  80313. var vertices = [];
  80314. vertices.push(1, 1);
  80315. vertices.push(-1, 1);
  80316. vertices.push(-1, -1);
  80317. vertices.push(1, -1);
  80318. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80319. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80320. this._createIndexBuffer();
  80321. // Effects
  80322. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  80323. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  80324. }
  80325. Object.defineProperty(Layer.prototype, "onDispose", {
  80326. set: function (callback) {
  80327. if (this._onDisposeObserver) {
  80328. this.onDisposeObservable.remove(this._onDisposeObserver);
  80329. }
  80330. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  80331. },
  80332. enumerable: true,
  80333. configurable: true
  80334. });
  80335. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  80336. set: function (callback) {
  80337. if (this._onBeforeRenderObserver) {
  80338. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  80339. }
  80340. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  80341. },
  80342. enumerable: true,
  80343. configurable: true
  80344. });
  80345. Object.defineProperty(Layer.prototype, "onAfterRender", {
  80346. set: function (callback) {
  80347. if (this._onAfterRenderObserver) {
  80348. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80349. }
  80350. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  80351. },
  80352. enumerable: true,
  80353. configurable: true
  80354. });
  80355. Layer.prototype._createIndexBuffer = function () {
  80356. var engine = this._scene.getEngine();
  80357. // Indices
  80358. var indices = [];
  80359. indices.push(0);
  80360. indices.push(1);
  80361. indices.push(2);
  80362. indices.push(0);
  80363. indices.push(2);
  80364. indices.push(3);
  80365. this._indexBuffer = engine.createIndexBuffer(indices);
  80366. };
  80367. Layer.prototype._rebuild = function () {
  80368. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80369. if (vb) {
  80370. vb._rebuild();
  80371. }
  80372. this._createIndexBuffer();
  80373. };
  80374. Layer.prototype.render = function () {
  80375. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  80376. // Check
  80377. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  80378. return;
  80379. var engine = this._scene.getEngine();
  80380. this.onBeforeRenderObservable.notifyObservers(this);
  80381. // Render
  80382. engine.enableEffect(currentEffect);
  80383. engine.setState(false);
  80384. // Texture
  80385. currentEffect.setTexture("textureSampler", this.texture);
  80386. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  80387. // Color
  80388. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  80389. // Scale / offset
  80390. currentEffect.setVector2("offset", this.offset);
  80391. currentEffect.setVector2("scale", this.scale);
  80392. // VBOs
  80393. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  80394. // Draw order
  80395. if (!this.alphaTest) {
  80396. engine.setAlphaMode(this.alphaBlendingMode);
  80397. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80398. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80399. }
  80400. else {
  80401. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80402. }
  80403. this.onAfterRenderObservable.notifyObservers(this);
  80404. };
  80405. Layer.prototype.dispose = function () {
  80406. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80407. if (vertexBuffer) {
  80408. vertexBuffer.dispose();
  80409. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80410. }
  80411. if (this._indexBuffer) {
  80412. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80413. this._indexBuffer = null;
  80414. }
  80415. if (this.texture) {
  80416. this.texture.dispose();
  80417. this.texture = null;
  80418. }
  80419. // Remove from scene
  80420. var index = this._scene.layers.indexOf(this);
  80421. this._scene.layers.splice(index, 1);
  80422. // Callback
  80423. this.onDisposeObservable.notifyObservers(this);
  80424. this.onDisposeObservable.clear();
  80425. this.onAfterRenderObservable.clear();
  80426. this.onBeforeRenderObservable.clear();
  80427. };
  80428. return Layer;
  80429. }());
  80430. BABYLON.Layer = Layer;
  80431. })(BABYLON || (BABYLON = {}));
  80432. //# sourceMappingURL=babylon.layer.js.map
  80433. var BABYLON;
  80434. (function (BABYLON) {
  80435. var TextureTools = /** @class */ (function () {
  80436. function TextureTools() {
  80437. }
  80438. /**
  80439. * Uses the GPU to create a copy texture rescaled at a given size
  80440. * @param texture Texture to copy from
  80441. * @param width Desired width
  80442. * @param height Desired height
  80443. * @return Generated texture
  80444. */
  80445. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  80446. if (useBilinearMode === void 0) { useBilinearMode = true; }
  80447. var scene = texture.getScene();
  80448. var engine = scene.getEngine();
  80449. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  80450. rtt.wrapU = texture.wrapU;
  80451. rtt.wrapV = texture.wrapV;
  80452. rtt.uOffset = texture.uOffset;
  80453. rtt.vOffset = texture.vOffset;
  80454. rtt.uScale = texture.uScale;
  80455. rtt.vScale = texture.vScale;
  80456. rtt.uAng = texture.uAng;
  80457. rtt.vAng = texture.vAng;
  80458. rtt.wAng = texture.wAng;
  80459. rtt.coordinatesIndex = texture.coordinatesIndex;
  80460. rtt.level = texture.level;
  80461. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  80462. rtt._texture.isReady = false;
  80463. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80464. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80465. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  80466. passPostProcess.getEffect().executeWhenCompiled(function () {
  80467. passPostProcess.onApply = function (effect) {
  80468. effect.setTexture("textureSampler", texture);
  80469. };
  80470. var internalTexture = rtt.getInternalTexture();
  80471. if (internalTexture) {
  80472. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  80473. engine.unBindFramebuffer(internalTexture);
  80474. rtt.disposeFramebufferObjects();
  80475. passPostProcess.dispose();
  80476. internalTexture.isReady = true;
  80477. }
  80478. });
  80479. return rtt;
  80480. };
  80481. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  80482. if (!scene._environmentBRDFTexture) {
  80483. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80484. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80485. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80486. scene._environmentBRDFTexture = texture;
  80487. }
  80488. return scene._environmentBRDFTexture;
  80489. };
  80490. 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=";
  80491. return TextureTools;
  80492. }());
  80493. BABYLON.TextureTools = TextureTools;
  80494. })(BABYLON || (BABYLON = {}));
  80495. //# sourceMappingURL=babylon.textureTools.js.map
  80496. var BABYLON;
  80497. (function (BABYLON) {
  80498. var FramingBehavior = /** @class */ (function () {
  80499. function FramingBehavior() {
  80500. this._mode = FramingBehavior.FitFrustumSidesMode;
  80501. this._radiusScale = 1.0;
  80502. this._positionScale = 0.5;
  80503. this._defaultElevation = 0.3;
  80504. this._elevationReturnTime = 1500;
  80505. this._elevationReturnWaitTime = 1000;
  80506. this._zoomStopsAnimation = false;
  80507. this._framingTime = 1500;
  80508. this._isPointerDown = false;
  80509. this._lastInteractionTime = -Infinity;
  80510. // Framing control
  80511. this._animatables = new Array();
  80512. this._betaIsAnimating = false;
  80513. }
  80514. Object.defineProperty(FramingBehavior.prototype, "name", {
  80515. get: function () {
  80516. return "Framing";
  80517. },
  80518. enumerable: true,
  80519. configurable: true
  80520. });
  80521. Object.defineProperty(FramingBehavior.prototype, "mode", {
  80522. /**
  80523. * Gets current mode used by the behavior.
  80524. */
  80525. get: function () {
  80526. return this._mode;
  80527. },
  80528. /**
  80529. * Sets the current mode used by the behavior
  80530. */
  80531. set: function (mode) {
  80532. this._mode = mode;
  80533. },
  80534. enumerable: true,
  80535. configurable: true
  80536. });
  80537. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  80538. /**
  80539. * Gets the scale applied to the radius
  80540. */
  80541. get: function () {
  80542. return this._radiusScale;
  80543. },
  80544. /**
  80545. * Sets the scale applied to the radius (1 by default)
  80546. */
  80547. set: function (radius) {
  80548. this._radiusScale = radius;
  80549. },
  80550. enumerable: true,
  80551. configurable: true
  80552. });
  80553. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  80554. /**
  80555. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80556. */
  80557. get: function () {
  80558. return this._positionScale;
  80559. },
  80560. /**
  80561. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  80562. */
  80563. set: function (scale) {
  80564. this._positionScale = scale;
  80565. },
  80566. enumerable: true,
  80567. configurable: true
  80568. });
  80569. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  80570. /**
  80571. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80572. * behaviour is triggered, in radians.
  80573. */
  80574. get: function () {
  80575. return this._defaultElevation;
  80576. },
  80577. /**
  80578. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  80579. * behaviour is triggered, in radians.
  80580. */
  80581. set: function (elevation) {
  80582. this._defaultElevation = elevation;
  80583. },
  80584. enumerable: true,
  80585. configurable: true
  80586. });
  80587. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  80588. /**
  80589. * Gets the time (in milliseconds) taken to return to the default beta position.
  80590. * Negative value indicates camera should not return to default.
  80591. */
  80592. get: function () {
  80593. return this._elevationReturnTime;
  80594. },
  80595. /**
  80596. * Sets the time (in milliseconds) taken to return to the default beta position.
  80597. * Negative value indicates camera should not return to default.
  80598. */
  80599. set: function (speed) {
  80600. this._elevationReturnTime = speed;
  80601. },
  80602. enumerable: true,
  80603. configurable: true
  80604. });
  80605. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  80606. /**
  80607. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80608. */
  80609. get: function () {
  80610. return this._elevationReturnWaitTime;
  80611. },
  80612. /**
  80613. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  80614. */
  80615. set: function (time) {
  80616. this._elevationReturnWaitTime = time;
  80617. },
  80618. enumerable: true,
  80619. configurable: true
  80620. });
  80621. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  80622. /**
  80623. * Gets the flag that indicates if user zooming should stop animation.
  80624. */
  80625. get: function () {
  80626. return this._zoomStopsAnimation;
  80627. },
  80628. /**
  80629. * Sets the flag that indicates if user zooming should stop animation.
  80630. */
  80631. set: function (flag) {
  80632. this._zoomStopsAnimation = flag;
  80633. },
  80634. enumerable: true,
  80635. configurable: true
  80636. });
  80637. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  80638. /**
  80639. * Gets the transition time when framing the mesh, in milliseconds
  80640. */
  80641. get: function () {
  80642. return this._framingTime;
  80643. },
  80644. /**
  80645. * Sets the transition time when framing the mesh, in milliseconds
  80646. */
  80647. set: function (time) {
  80648. this._framingTime = time;
  80649. },
  80650. enumerable: true,
  80651. configurable: true
  80652. });
  80653. FramingBehavior.prototype.init = function () {
  80654. // Do notihng
  80655. };
  80656. FramingBehavior.prototype.attach = function (camera) {
  80657. var _this = this;
  80658. this._attachedCamera = camera;
  80659. var scene = this._attachedCamera.getScene();
  80660. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  80661. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  80662. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  80663. _this._isPointerDown = true;
  80664. return;
  80665. }
  80666. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  80667. _this._isPointerDown = false;
  80668. }
  80669. });
  80670. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  80671. if (mesh) {
  80672. _this.zoomOnMesh(mesh);
  80673. }
  80674. });
  80675. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  80676. // Stop the animation if there is user interaction and the animation should stop for this interaction
  80677. _this._applyUserInteraction();
  80678. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  80679. // back to the default position after a given timeout
  80680. _this._maintainCameraAboveGround();
  80681. });
  80682. };
  80683. FramingBehavior.prototype.detach = function () {
  80684. if (!this._attachedCamera) {
  80685. return;
  80686. }
  80687. var scene = this._attachedCamera.getScene();
  80688. if (this._onPrePointerObservableObserver) {
  80689. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  80690. }
  80691. if (this._onAfterCheckInputsObserver) {
  80692. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  80693. }
  80694. if (this._onMeshTargetChangedObserver) {
  80695. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  80696. }
  80697. this._attachedCamera = null;
  80698. };
  80699. /**
  80700. * Targets the given mesh and updates zoom level accordingly.
  80701. * @param mesh The mesh to target.
  80702. * @param radius Optional. If a cached radius position already exists, overrides default.
  80703. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80704. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80705. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80706. */
  80707. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  80708. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80709. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80710. mesh.computeWorldMatrix(true);
  80711. var boundingBox = mesh.getBoundingInfo().boundingBox;
  80712. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  80713. };
  80714. /**
  80715. * Targets the given mesh with its children and updates zoom level accordingly.
  80716. * @param mesh The mesh to target.
  80717. * @param radius Optional. If a cached radius position already exists, overrides default.
  80718. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80719. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80720. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80721. */
  80722. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  80723. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80724. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80725. mesh.computeWorldMatrix(true);
  80726. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  80727. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  80728. };
  80729. /**
  80730. * Targets the given meshes with their children and updates zoom level accordingly.
  80731. * @param meshes The mesh to target.
  80732. * @param radius Optional. If a cached radius position already exists, overrides default.
  80733. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80734. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80735. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80736. */
  80737. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  80738. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80739. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80740. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  80741. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  80742. for (var i = 0; i < meshes.length; i++) {
  80743. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  80744. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  80745. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  80746. }
  80747. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  80748. };
  80749. /**
  80750. * Targets the given mesh and updates zoom level accordingly.
  80751. * @param mesh The mesh to target.
  80752. * @param radius Optional. If a cached radius position already exists, overrides default.
  80753. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  80754. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  80755. * @param onAnimationEnd Callback triggered at the end of the framing animation
  80756. */
  80757. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  80758. var _this = this;
  80759. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  80760. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  80761. var zoomTarget;
  80762. if (!this._attachedCamera) {
  80763. return;
  80764. }
  80765. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  80766. var bottom = minimumWorld.y;
  80767. var top = maximumWorld.y;
  80768. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  80769. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  80770. if (focusOnOriginXZ) {
  80771. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  80772. }
  80773. else {
  80774. var centerWorld = minimumWorld.add(radiusWorld);
  80775. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  80776. }
  80777. if (!this._vectorTransition) {
  80778. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  80779. }
  80780. this._betaIsAnimating = true;
  80781. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  80782. if (animatable) {
  80783. this._animatables.push(animatable);
  80784. }
  80785. // sets the radius and lower radius bounds
  80786. // Small delta ensures camera is not always at lower zoom limit.
  80787. var radius = 0;
  80788. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  80789. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  80790. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  80791. radius = position;
  80792. }
  80793. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  80794. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  80795. if (this._attachedCamera.lowerRadiusLimit === null) {
  80796. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  80797. }
  80798. }
  80799. // Set sensibilities
  80800. var extend = maximumWorld.subtract(minimumWorld).length();
  80801. this._attachedCamera.panningSensibility = 5000 / extend;
  80802. this._attachedCamera.wheelPrecision = 100 / radius;
  80803. // transition to new radius
  80804. if (!this._radiusTransition) {
  80805. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  80806. }
  80807. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  80808. if (onAnimationEnd) {
  80809. onAnimationEnd();
  80810. }
  80811. if (_this._attachedCamera) {
  80812. _this._attachedCamera.storeState();
  80813. }
  80814. });
  80815. if (animatable) {
  80816. this._animatables.push(animatable);
  80817. }
  80818. };
  80819. /**
  80820. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  80821. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  80822. * frustum width.
  80823. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  80824. * to fully enclose the mesh in the viewing frustum.
  80825. */
  80826. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  80827. var size = maximumWorld.subtract(minimumWorld);
  80828. var boxVectorGlobalDiagonal = size.length();
  80829. var frustumSlope = this._getFrustumSlope();
  80830. // Formula for setting distance
  80831. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  80832. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  80833. // Horizon distance
  80834. var radius = radiusWithoutFraming * this._radiusScale;
  80835. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  80836. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  80837. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  80838. var camera = this._attachedCamera;
  80839. if (!camera) {
  80840. return 0;
  80841. }
  80842. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  80843. // Don't exceed the requested limit
  80844. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  80845. }
  80846. // Don't exceed the upper radius limit
  80847. if (camera.upperRadiusLimit) {
  80848. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  80849. }
  80850. return distance;
  80851. };
  80852. /**
  80853. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  80854. * is automatically returned to its default position (expected to be above ground plane).
  80855. */
  80856. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  80857. var _this = this;
  80858. if (this._elevationReturnTime < 0) {
  80859. return;
  80860. }
  80861. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  80862. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  80863. var limitBeta = Math.PI * 0.5;
  80864. // Bring the camera back up if below the ground plane
  80865. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  80866. this._betaIsAnimating = true;
  80867. //Transition to new position
  80868. this.stopAllAnimations();
  80869. if (!this._betaTransition) {
  80870. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  80871. }
  80872. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  80873. _this._clearAnimationLocks();
  80874. _this.stopAllAnimations();
  80875. });
  80876. if (animatabe) {
  80877. this._animatables.push(animatabe);
  80878. }
  80879. }
  80880. };
  80881. /**
  80882. * Returns the frustum slope based on the canvas ratio and camera FOV
  80883. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  80884. */
  80885. FramingBehavior.prototype._getFrustumSlope = function () {
  80886. // Calculate the viewport ratio
  80887. // Aspect Ratio is Height/Width.
  80888. var camera = this._attachedCamera;
  80889. if (!camera) {
  80890. return BABYLON.Vector2.Zero();
  80891. }
  80892. var engine = camera.getScene().getEngine();
  80893. var aspectRatio = engine.getAspectRatio(camera);
  80894. // Camera FOV is the vertical field of view (top-bottom) in radians.
  80895. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  80896. var frustumSlopeY = Math.tan(camera.fov / 2);
  80897. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  80898. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  80899. // along the forward vector.
  80900. var frustumSlopeX = frustumSlopeY * aspectRatio;
  80901. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  80902. };
  80903. /**
  80904. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  80905. */
  80906. FramingBehavior.prototype._clearAnimationLocks = function () {
  80907. this._betaIsAnimating = false;
  80908. };
  80909. /**
  80910. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  80911. */
  80912. FramingBehavior.prototype._applyUserInteraction = function () {
  80913. if (this.isUserIsMoving) {
  80914. this._lastInteractionTime = BABYLON.Tools.Now;
  80915. this.stopAllAnimations();
  80916. this._clearAnimationLocks();
  80917. }
  80918. };
  80919. /**
  80920. * Stops and removes all animations that have been applied to the camera
  80921. */
  80922. FramingBehavior.prototype.stopAllAnimations = function () {
  80923. if (this._attachedCamera) {
  80924. this._attachedCamera.animations = [];
  80925. }
  80926. while (this._animatables.length) {
  80927. if (this._animatables[0]) {
  80928. this._animatables[0].onAnimationEnd = null;
  80929. this._animatables[0].stop();
  80930. }
  80931. this._animatables.shift();
  80932. }
  80933. };
  80934. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  80935. /**
  80936. * Gets a value indicating if the user is moving the camera
  80937. */
  80938. get: function () {
  80939. if (!this._attachedCamera) {
  80940. return false;
  80941. }
  80942. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  80943. this._attachedCamera.inertialBetaOffset !== 0 ||
  80944. this._attachedCamera.inertialRadiusOffset !== 0 ||
  80945. this._attachedCamera.inertialPanningX !== 0 ||
  80946. this._attachedCamera.inertialPanningY !== 0 ||
  80947. this._isPointerDown;
  80948. },
  80949. enumerable: true,
  80950. configurable: true
  80951. });
  80952. /**
  80953. * The easing function used by animations
  80954. */
  80955. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  80956. /**
  80957. * The easing mode used by animations
  80958. */
  80959. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  80960. // Statics
  80961. /**
  80962. * The camera can move all the way towards the mesh.
  80963. */
  80964. FramingBehavior.IgnoreBoundsSizeMode = 0;
  80965. /**
  80966. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  80967. */
  80968. FramingBehavior.FitFrustumSidesMode = 1;
  80969. return FramingBehavior;
  80970. }());
  80971. BABYLON.FramingBehavior = FramingBehavior;
  80972. })(BABYLON || (BABYLON = {}));
  80973. //# sourceMappingURL=babylon.framingBehavior.js.map
  80974. var BABYLON;
  80975. (function (BABYLON) {
  80976. /**
  80977. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  80978. */
  80979. var BouncingBehavior = /** @class */ (function () {
  80980. function BouncingBehavior() {
  80981. /**
  80982. * The duration of the animation, in milliseconds
  80983. */
  80984. this.transitionDuration = 450;
  80985. /**
  80986. * Length of the distance animated by the transition when lower radius is reached
  80987. */
  80988. this.lowerRadiusTransitionRange = 2;
  80989. /**
  80990. * Length of the distance animated by the transition when upper radius is reached
  80991. */
  80992. this.upperRadiusTransitionRange = -2;
  80993. this._autoTransitionRange = false;
  80994. // Animations
  80995. this._radiusIsAnimating = false;
  80996. this._radiusBounceTransition = null;
  80997. this._animatables = new Array();
  80998. }
  80999. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81000. get: function () {
  81001. return "Bouncing";
  81002. },
  81003. enumerable: true,
  81004. configurable: true
  81005. });
  81006. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81007. /**
  81008. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81009. */
  81010. get: function () {
  81011. return this._autoTransitionRange;
  81012. },
  81013. /**
  81014. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81015. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81016. */
  81017. set: function (value) {
  81018. var _this = this;
  81019. if (this._autoTransitionRange === value) {
  81020. return;
  81021. }
  81022. this._autoTransitionRange = value;
  81023. var camera = this._attachedCamera;
  81024. if (!camera) {
  81025. return;
  81026. }
  81027. if (value) {
  81028. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81029. if (!mesh) {
  81030. return;
  81031. }
  81032. mesh.computeWorldMatrix(true);
  81033. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81034. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81035. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81036. });
  81037. }
  81038. else if (this._onMeshTargetChangedObserver) {
  81039. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81040. }
  81041. },
  81042. enumerable: true,
  81043. configurable: true
  81044. });
  81045. BouncingBehavior.prototype.init = function () {
  81046. // Do notihng
  81047. };
  81048. BouncingBehavior.prototype.attach = function (camera) {
  81049. var _this = this;
  81050. this._attachedCamera = camera;
  81051. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81052. if (!_this._attachedCamera) {
  81053. return;
  81054. }
  81055. // Add the bounce animation to the lower radius limit
  81056. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  81057. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  81058. }
  81059. // Add the bounce animation to the upper radius limit
  81060. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  81061. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  81062. }
  81063. });
  81064. };
  81065. BouncingBehavior.prototype.detach = function () {
  81066. if (!this._attachedCamera) {
  81067. return;
  81068. }
  81069. if (this._onAfterCheckInputsObserver) {
  81070. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81071. }
  81072. if (this._onMeshTargetChangedObserver) {
  81073. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81074. }
  81075. this._attachedCamera = null;
  81076. };
  81077. /**
  81078. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  81079. * @param radiusLimit The limit to check against.
  81080. * @return Bool to indicate if at limit.
  81081. */
  81082. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  81083. if (!this._attachedCamera) {
  81084. return false;
  81085. }
  81086. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  81087. return true;
  81088. }
  81089. return false;
  81090. };
  81091. /**
  81092. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  81093. * @param radiusDelta The delta by which to animate to. Can be negative.
  81094. */
  81095. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  81096. var _this = this;
  81097. if (!this._attachedCamera) {
  81098. return;
  81099. }
  81100. if (!this._radiusBounceTransition) {
  81101. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  81102. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  81103. }
  81104. // Prevent zoom until bounce has completed
  81105. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  81106. this._attachedCamera.wheelPrecision = Infinity;
  81107. this._attachedCamera.inertialRadiusOffset = 0;
  81108. // Animate to the radius limit
  81109. this.stopAllAnimations();
  81110. this._radiusIsAnimating = true;
  81111. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  81112. if (animatable) {
  81113. this._animatables.push(animatable);
  81114. }
  81115. };
  81116. /**
  81117. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  81118. */
  81119. BouncingBehavior.prototype._clearAnimationLocks = function () {
  81120. this._radiusIsAnimating = false;
  81121. if (this._attachedCamera) {
  81122. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  81123. }
  81124. };
  81125. /**
  81126. * Stops and removes all animations that have been applied to the camera
  81127. */
  81128. BouncingBehavior.prototype.stopAllAnimations = function () {
  81129. if (this._attachedCamera) {
  81130. this._attachedCamera.animations = [];
  81131. }
  81132. while (this._animatables.length) {
  81133. this._animatables[0].onAnimationEnd = null;
  81134. this._animatables[0].stop();
  81135. this._animatables.shift();
  81136. }
  81137. };
  81138. /**
  81139. * The easing function used by animations
  81140. */
  81141. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  81142. /**
  81143. * The easing mode used by animations
  81144. */
  81145. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  81146. return BouncingBehavior;
  81147. }());
  81148. BABYLON.BouncingBehavior = BouncingBehavior;
  81149. })(BABYLON || (BABYLON = {}));
  81150. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  81151. var BABYLON;
  81152. (function (BABYLON) {
  81153. var AutoRotationBehavior = /** @class */ (function () {
  81154. function AutoRotationBehavior() {
  81155. this._zoomStopsAnimation = false;
  81156. this._idleRotationSpeed = 0.05;
  81157. this._idleRotationWaitTime = 2000;
  81158. this._idleRotationSpinupTime = 2000;
  81159. this._isPointerDown = false;
  81160. this._lastFrameTime = null;
  81161. this._lastInteractionTime = -Infinity;
  81162. this._cameraRotationSpeed = 0;
  81163. this._lastFrameRadius = 0;
  81164. }
  81165. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  81166. get: function () {
  81167. return "AutoRotation";
  81168. },
  81169. enumerable: true,
  81170. configurable: true
  81171. });
  81172. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  81173. /**
  81174. * Gets the flag that indicates if user zooming should stop animation.
  81175. */
  81176. get: function () {
  81177. return this._zoomStopsAnimation;
  81178. },
  81179. /**
  81180. * Sets the flag that indicates if user zooming should stop animation.
  81181. */
  81182. set: function (flag) {
  81183. this._zoomStopsAnimation = flag;
  81184. },
  81185. enumerable: true,
  81186. configurable: true
  81187. });
  81188. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  81189. /**
  81190. * Gets the default speed at which the camera rotates around the model.
  81191. */
  81192. get: function () {
  81193. return this._idleRotationSpeed;
  81194. },
  81195. /**
  81196. * Sets the default speed at which the camera rotates around the model.
  81197. */
  81198. set: function (speed) {
  81199. this._idleRotationSpeed = speed;
  81200. },
  81201. enumerable: true,
  81202. configurable: true
  81203. });
  81204. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  81205. /**
  81206. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  81207. */
  81208. get: function () {
  81209. return this._idleRotationWaitTime;
  81210. },
  81211. /**
  81212. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  81213. */
  81214. set: function (time) {
  81215. this._idleRotationWaitTime = time;
  81216. },
  81217. enumerable: true,
  81218. configurable: true
  81219. });
  81220. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  81221. /**
  81222. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81223. */
  81224. get: function () {
  81225. return this._idleRotationSpinupTime;
  81226. },
  81227. /**
  81228. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81229. */
  81230. set: function (time) {
  81231. this._idleRotationSpinupTime = time;
  81232. },
  81233. enumerable: true,
  81234. configurable: true
  81235. });
  81236. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  81237. /**
  81238. * Gets a value indicating if the camera is currently rotating because of this behavior
  81239. */
  81240. get: function () {
  81241. return Math.abs(this._cameraRotationSpeed) > 0;
  81242. },
  81243. enumerable: true,
  81244. configurable: true
  81245. });
  81246. AutoRotationBehavior.prototype.init = function () {
  81247. // Do notihng
  81248. };
  81249. AutoRotationBehavior.prototype.attach = function (camera) {
  81250. var _this = this;
  81251. this._attachedCamera = camera;
  81252. var scene = this._attachedCamera.getScene();
  81253. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81254. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81255. _this._isPointerDown = true;
  81256. return;
  81257. }
  81258. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81259. _this._isPointerDown = false;
  81260. }
  81261. });
  81262. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81263. var now = BABYLON.Tools.Now;
  81264. var dt = 0;
  81265. if (_this._lastFrameTime != null) {
  81266. dt = now - _this._lastFrameTime;
  81267. }
  81268. _this._lastFrameTime = now;
  81269. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81270. _this._applyUserInteraction();
  81271. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  81272. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  81273. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  81274. // Step camera rotation by rotation speed
  81275. if (_this._attachedCamera) {
  81276. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  81277. }
  81278. });
  81279. };
  81280. AutoRotationBehavior.prototype.detach = function () {
  81281. if (!this._attachedCamera) {
  81282. return;
  81283. }
  81284. var scene = this._attachedCamera.getScene();
  81285. if (this._onPrePointerObservableObserver) {
  81286. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81287. }
  81288. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81289. this._attachedCamera = null;
  81290. };
  81291. /**
  81292. * Returns true if user is scrolling.
  81293. * @return true if user is scrolling.
  81294. */
  81295. AutoRotationBehavior.prototype._userIsZooming = function () {
  81296. if (!this._attachedCamera) {
  81297. return false;
  81298. }
  81299. return this._attachedCamera.inertialRadiusOffset !== 0;
  81300. };
  81301. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  81302. if (!this._attachedCamera) {
  81303. return false;
  81304. }
  81305. var zoomHasHitLimit = false;
  81306. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  81307. zoomHasHitLimit = true;
  81308. }
  81309. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  81310. this._lastFrameRadius = this._attachedCamera.radius;
  81311. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  81312. };
  81313. /**
  81314. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81315. */
  81316. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  81317. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  81318. this._lastInteractionTime = BABYLON.Tools.Now;
  81319. }
  81320. };
  81321. // Tools
  81322. AutoRotationBehavior.prototype._userIsMoving = function () {
  81323. if (!this._attachedCamera) {
  81324. return false;
  81325. }
  81326. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81327. this._attachedCamera.inertialBetaOffset !== 0 ||
  81328. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81329. this._attachedCamera.inertialPanningX !== 0 ||
  81330. this._attachedCamera.inertialPanningY !== 0 ||
  81331. this._isPointerDown;
  81332. };
  81333. return AutoRotationBehavior;
  81334. }());
  81335. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  81336. })(BABYLON || (BABYLON = {}));
  81337. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  81338. var BABYLON;
  81339. (function (BABYLON) {
  81340. /**
  81341. * This class can be used to get instrumentation data from a Babylon engine
  81342. */
  81343. var EngineInstrumentation = /** @class */ (function () {
  81344. function EngineInstrumentation(engine) {
  81345. this.engine = engine;
  81346. this._captureGPUFrameTime = false;
  81347. this._gpuFrameTime = new BABYLON.PerfCounter();
  81348. this._captureShaderCompilationTime = false;
  81349. this._shaderCompilationTime = new BABYLON.PerfCounter();
  81350. // Observers
  81351. this._onBeginFrameObserver = null;
  81352. this._onEndFrameObserver = null;
  81353. this._onBeforeShaderCompilationObserver = null;
  81354. this._onAfterShaderCompilationObserver = null;
  81355. }
  81356. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  81357. // Properties
  81358. /**
  81359. * Gets the perf counter used for GPU frame time
  81360. */
  81361. get: function () {
  81362. return this._gpuFrameTime;
  81363. },
  81364. enumerable: true,
  81365. configurable: true
  81366. });
  81367. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  81368. /**
  81369. * Gets the GPU frame time capture status
  81370. */
  81371. get: function () {
  81372. return this._captureGPUFrameTime;
  81373. },
  81374. /**
  81375. * Enable or disable the GPU frame time capture
  81376. */
  81377. set: function (value) {
  81378. var _this = this;
  81379. if (value === this._captureGPUFrameTime) {
  81380. return;
  81381. }
  81382. this._captureGPUFrameTime = value;
  81383. if (value) {
  81384. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  81385. if (!_this._gpuFrameTimeToken) {
  81386. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  81387. }
  81388. });
  81389. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  81390. if (!_this._gpuFrameTimeToken) {
  81391. return;
  81392. }
  81393. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  81394. if (time > -1) {
  81395. _this._gpuFrameTimeToken = null;
  81396. _this._gpuFrameTime.fetchNewFrame();
  81397. _this._gpuFrameTime.addCount(time, true);
  81398. }
  81399. });
  81400. }
  81401. else {
  81402. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81403. this._onBeginFrameObserver = null;
  81404. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81405. this._onEndFrameObserver = null;
  81406. }
  81407. },
  81408. enumerable: true,
  81409. configurable: true
  81410. });
  81411. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  81412. /**
  81413. * Gets the perf counter used for shader compilation time
  81414. */
  81415. get: function () {
  81416. return this._shaderCompilationTime;
  81417. },
  81418. enumerable: true,
  81419. configurable: true
  81420. });
  81421. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  81422. /**
  81423. * Gets the shader compilation time capture status
  81424. */
  81425. get: function () {
  81426. return this._captureShaderCompilationTime;
  81427. },
  81428. /**
  81429. * Enable or disable the shader compilation time capture
  81430. */
  81431. set: function (value) {
  81432. var _this = this;
  81433. if (value === this._captureShaderCompilationTime) {
  81434. return;
  81435. }
  81436. this._captureShaderCompilationTime = value;
  81437. if (value) {
  81438. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  81439. _this._shaderCompilationTime.fetchNewFrame();
  81440. _this._shaderCompilationTime.beginMonitoring();
  81441. });
  81442. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  81443. _this._shaderCompilationTime.endMonitoring();
  81444. });
  81445. }
  81446. else {
  81447. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81448. this._onBeforeShaderCompilationObserver = null;
  81449. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81450. this._onAfterShaderCompilationObserver = null;
  81451. }
  81452. },
  81453. enumerable: true,
  81454. configurable: true
  81455. });
  81456. EngineInstrumentation.prototype.dispose = function () {
  81457. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  81458. this._onBeginFrameObserver = null;
  81459. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  81460. this._onEndFrameObserver = null;
  81461. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  81462. this._onBeforeShaderCompilationObserver = null;
  81463. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  81464. this._onAfterShaderCompilationObserver = null;
  81465. this.engine = null;
  81466. };
  81467. return EngineInstrumentation;
  81468. }());
  81469. BABYLON.EngineInstrumentation = EngineInstrumentation;
  81470. })(BABYLON || (BABYLON = {}));
  81471. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  81472. var BABYLON;
  81473. (function (BABYLON) {
  81474. /**
  81475. * This class can be used to get instrumentation data from a Babylon engine
  81476. */
  81477. var SceneInstrumentation = /** @class */ (function () {
  81478. function SceneInstrumentation(scene) {
  81479. var _this = this;
  81480. this.scene = scene;
  81481. this._captureActiveMeshesEvaluationTime = false;
  81482. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  81483. this._captureRenderTargetsRenderTime = false;
  81484. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  81485. this._captureFrameTime = false;
  81486. this._frameTime = new BABYLON.PerfCounter();
  81487. this._captureRenderTime = false;
  81488. this._renderTime = new BABYLON.PerfCounter();
  81489. this._captureInterFrameTime = false;
  81490. this._interFrameTime = new BABYLON.PerfCounter();
  81491. this._captureParticlesRenderTime = false;
  81492. this._particlesRenderTime = new BABYLON.PerfCounter();
  81493. this._captureSpritesRenderTime = false;
  81494. this._spritesRenderTime = new BABYLON.PerfCounter();
  81495. this._capturePhysicsTime = false;
  81496. this._physicsTime = new BABYLON.PerfCounter();
  81497. this._captureAnimationsTime = false;
  81498. this._animationsTime = new BABYLON.PerfCounter();
  81499. // Observers
  81500. this._onBeforeActiveMeshesEvaluationObserver = null;
  81501. this._onAfterActiveMeshesEvaluationObserver = null;
  81502. this._onBeforeRenderTargetsRenderObserver = null;
  81503. this._onAfterRenderTargetsRenderObserver = null;
  81504. this._onAfterRenderObserver = null;
  81505. this._onBeforeDrawPhaseObserver = null;
  81506. this._onAfterDrawPhaseObserver = null;
  81507. this._onBeforeAnimationsObserver = null;
  81508. this._onBeforeParticlesRenderingObserver = null;
  81509. this._onAfterParticlesRenderingObserver = null;
  81510. this._onBeforeSpritesRenderingObserver = null;
  81511. this._onAfterSpritesRenderingObserver = null;
  81512. this._onBeforePhysicsObserver = null;
  81513. this._onAfterPhysicsObserver = null;
  81514. this._onAfterAnimationsObserver = null;
  81515. // Before render
  81516. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  81517. if (_this._captureActiveMeshesEvaluationTime) {
  81518. _this._activeMeshesEvaluationTime.fetchNewFrame();
  81519. }
  81520. if (_this._captureRenderTargetsRenderTime) {
  81521. _this._renderTargetsRenderTime.fetchNewFrame();
  81522. }
  81523. if (_this._captureFrameTime) {
  81524. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  81525. _this._frameTime.beginMonitoring();
  81526. }
  81527. if (_this._captureInterFrameTime) {
  81528. _this._interFrameTime.endMonitoring();
  81529. }
  81530. if (_this._captureParticlesRenderTime) {
  81531. _this._particlesRenderTime.fetchNewFrame();
  81532. }
  81533. if (_this._captureSpritesRenderTime) {
  81534. _this._spritesRenderTime.fetchNewFrame();
  81535. }
  81536. if (_this._captureAnimationsTime) {
  81537. _this._animationsTime.beginMonitoring();
  81538. }
  81539. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  81540. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  81541. });
  81542. // After render
  81543. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  81544. if (_this._captureFrameTime) {
  81545. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  81546. _this._frameTime.endMonitoring();
  81547. }
  81548. if (_this._captureRenderTime) {
  81549. _this._renderTime.endMonitoring(false);
  81550. }
  81551. if (_this._captureInterFrameTime) {
  81552. _this._interFrameTime.beginMonitoring();
  81553. }
  81554. });
  81555. }
  81556. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  81557. // Properties
  81558. /**
  81559. * Gets the perf counter used for active meshes evaluation time
  81560. */
  81561. get: function () {
  81562. return this._activeMeshesEvaluationTime;
  81563. },
  81564. enumerable: true,
  81565. configurable: true
  81566. });
  81567. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  81568. /**
  81569. * Gets the active meshes evaluation time capture status
  81570. */
  81571. get: function () {
  81572. return this._captureActiveMeshesEvaluationTime;
  81573. },
  81574. /**
  81575. * Enable or disable the active meshes evaluation time capture
  81576. */
  81577. set: function (value) {
  81578. var _this = this;
  81579. if (value === this._captureActiveMeshesEvaluationTime) {
  81580. return;
  81581. }
  81582. this._captureActiveMeshesEvaluationTime = value;
  81583. if (value) {
  81584. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  81585. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  81586. _this._activeMeshesEvaluationTime.beginMonitoring();
  81587. });
  81588. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  81589. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  81590. _this._activeMeshesEvaluationTime.endMonitoring();
  81591. });
  81592. }
  81593. else {
  81594. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  81595. this._onBeforeActiveMeshesEvaluationObserver = null;
  81596. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  81597. this._onAfterActiveMeshesEvaluationObserver = null;
  81598. }
  81599. },
  81600. enumerable: true,
  81601. configurable: true
  81602. });
  81603. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  81604. /**
  81605. * Gets the perf counter used for render targets render time
  81606. */
  81607. get: function () {
  81608. return this._renderTargetsRenderTime;
  81609. },
  81610. enumerable: true,
  81611. configurable: true
  81612. });
  81613. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  81614. /**
  81615. * Gets the render targets render time capture status
  81616. */
  81617. get: function () {
  81618. return this._captureRenderTargetsRenderTime;
  81619. },
  81620. /**
  81621. * Enable or disable the render targets render time capture
  81622. */
  81623. set: function (value) {
  81624. var _this = this;
  81625. if (value === this._captureRenderTargetsRenderTime) {
  81626. return;
  81627. }
  81628. this._captureRenderTargetsRenderTime = value;
  81629. if (value) {
  81630. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  81631. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  81632. _this._renderTargetsRenderTime.beginMonitoring();
  81633. });
  81634. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  81635. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  81636. _this._renderTargetsRenderTime.endMonitoring(false);
  81637. });
  81638. }
  81639. else {
  81640. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  81641. this._onBeforeRenderTargetsRenderObserver = null;
  81642. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  81643. this._onAfterRenderTargetsRenderObserver = null;
  81644. }
  81645. },
  81646. enumerable: true,
  81647. configurable: true
  81648. });
  81649. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  81650. /**
  81651. * Gets the perf counter used for particles render time
  81652. */
  81653. get: function () {
  81654. return this._particlesRenderTime;
  81655. },
  81656. enumerable: true,
  81657. configurable: true
  81658. });
  81659. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  81660. /**
  81661. * Gets the particles render time capture status
  81662. */
  81663. get: function () {
  81664. return this._captureParticlesRenderTime;
  81665. },
  81666. /**
  81667. * Enable or disable the particles render time capture
  81668. */
  81669. set: function (value) {
  81670. var _this = this;
  81671. if (value === this._captureParticlesRenderTime) {
  81672. return;
  81673. }
  81674. this._captureParticlesRenderTime = value;
  81675. if (value) {
  81676. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  81677. BABYLON.Tools.StartPerformanceCounter("Particles");
  81678. _this._particlesRenderTime.beginMonitoring();
  81679. });
  81680. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  81681. BABYLON.Tools.EndPerformanceCounter("Particles");
  81682. _this._particlesRenderTime.endMonitoring(false);
  81683. });
  81684. }
  81685. else {
  81686. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  81687. this._onBeforeParticlesRenderingObserver = null;
  81688. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  81689. this._onAfterParticlesRenderingObserver = null;
  81690. }
  81691. },
  81692. enumerable: true,
  81693. configurable: true
  81694. });
  81695. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  81696. /**
  81697. * Gets the perf counter used for sprites render time
  81698. */
  81699. get: function () {
  81700. return this._spritesRenderTime;
  81701. },
  81702. enumerable: true,
  81703. configurable: true
  81704. });
  81705. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  81706. /**
  81707. * Gets the sprites render time capture status
  81708. */
  81709. get: function () {
  81710. return this._captureSpritesRenderTime;
  81711. },
  81712. /**
  81713. * Enable or disable the sprites render time capture
  81714. */
  81715. set: function (value) {
  81716. var _this = this;
  81717. if (value === this._captureSpritesRenderTime) {
  81718. return;
  81719. }
  81720. this._captureSpritesRenderTime = value;
  81721. if (value) {
  81722. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  81723. BABYLON.Tools.StartPerformanceCounter("Sprites");
  81724. _this._spritesRenderTime.beginMonitoring();
  81725. });
  81726. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  81727. BABYLON.Tools.EndPerformanceCounter("Sprites");
  81728. _this._spritesRenderTime.endMonitoring(false);
  81729. });
  81730. }
  81731. else {
  81732. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  81733. this._onBeforeSpritesRenderingObserver = null;
  81734. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  81735. this._onAfterSpritesRenderingObserver = null;
  81736. }
  81737. },
  81738. enumerable: true,
  81739. configurable: true
  81740. });
  81741. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  81742. /**
  81743. * Gets the perf counter used for physics time
  81744. */
  81745. get: function () {
  81746. return this._physicsTime;
  81747. },
  81748. enumerable: true,
  81749. configurable: true
  81750. });
  81751. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  81752. /**
  81753. * Gets the physics time capture status
  81754. */
  81755. get: function () {
  81756. return this._capturePhysicsTime;
  81757. },
  81758. /**
  81759. * Enable or disable the physics time capture
  81760. */
  81761. set: function (value) {
  81762. var _this = this;
  81763. if (value === this._capturePhysicsTime) {
  81764. return;
  81765. }
  81766. this._capturePhysicsTime = value;
  81767. if (value) {
  81768. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  81769. BABYLON.Tools.StartPerformanceCounter("Physics");
  81770. _this._physicsTime.beginMonitoring();
  81771. });
  81772. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  81773. BABYLON.Tools.EndPerformanceCounter("Physics");
  81774. _this._physicsTime.endMonitoring();
  81775. });
  81776. }
  81777. else {
  81778. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  81779. this._onBeforePhysicsObserver = null;
  81780. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  81781. this._onAfterPhysicsObserver = null;
  81782. }
  81783. },
  81784. enumerable: true,
  81785. configurable: true
  81786. });
  81787. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  81788. /**
  81789. * Gets the perf counter used for animations time
  81790. */
  81791. get: function () {
  81792. return this._animationsTime;
  81793. },
  81794. enumerable: true,
  81795. configurable: true
  81796. });
  81797. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  81798. /**
  81799. * Gets the animations time capture status
  81800. */
  81801. get: function () {
  81802. return this._captureAnimationsTime;
  81803. },
  81804. /**
  81805. * Enable or disable the animations time capture
  81806. */
  81807. set: function (value) {
  81808. var _this = this;
  81809. if (value === this._captureAnimationsTime) {
  81810. return;
  81811. }
  81812. this._captureAnimationsTime = value;
  81813. if (value) {
  81814. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  81815. _this._animationsTime.endMonitoring();
  81816. });
  81817. }
  81818. else {
  81819. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  81820. this._onAfterAnimationsObserver = null;
  81821. }
  81822. },
  81823. enumerable: true,
  81824. configurable: true
  81825. });
  81826. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  81827. /**
  81828. * Gets the perf counter used for frame time capture
  81829. */
  81830. get: function () {
  81831. return this._frameTime;
  81832. },
  81833. enumerable: true,
  81834. configurable: true
  81835. });
  81836. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  81837. /**
  81838. * Gets the frame time capture status
  81839. */
  81840. get: function () {
  81841. return this._captureFrameTime;
  81842. },
  81843. /**
  81844. * Enable or disable the frame time capture
  81845. */
  81846. set: function (value) {
  81847. this._captureFrameTime = value;
  81848. },
  81849. enumerable: true,
  81850. configurable: true
  81851. });
  81852. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  81853. /**
  81854. * Gets the perf counter used for inter-frames time capture
  81855. */
  81856. get: function () {
  81857. return this._interFrameTime;
  81858. },
  81859. enumerable: true,
  81860. configurable: true
  81861. });
  81862. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  81863. /**
  81864. * Gets the inter-frames time capture status
  81865. */
  81866. get: function () {
  81867. return this._captureInterFrameTime;
  81868. },
  81869. /**
  81870. * Enable or disable the inter-frames time capture
  81871. */
  81872. set: function (value) {
  81873. this._captureInterFrameTime = value;
  81874. },
  81875. enumerable: true,
  81876. configurable: true
  81877. });
  81878. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  81879. /**
  81880. * Gets the perf counter used for render time capture
  81881. */
  81882. get: function () {
  81883. return this._renderTime;
  81884. },
  81885. enumerable: true,
  81886. configurable: true
  81887. });
  81888. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  81889. /**
  81890. * Gets the render time capture status
  81891. */
  81892. get: function () {
  81893. return this._captureRenderTime;
  81894. },
  81895. /**
  81896. * Enable or disable the render time capture
  81897. */
  81898. set: function (value) {
  81899. var _this = this;
  81900. if (value === this._captureRenderTime) {
  81901. return;
  81902. }
  81903. this._captureRenderTime = value;
  81904. if (value) {
  81905. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  81906. _this._renderTime.beginMonitoring();
  81907. BABYLON.Tools.StartPerformanceCounter("Main render");
  81908. });
  81909. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  81910. _this._renderTime.endMonitoring(false);
  81911. BABYLON.Tools.EndPerformanceCounter("Main render");
  81912. });
  81913. }
  81914. else {
  81915. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  81916. this._onBeforeDrawPhaseObserver = null;
  81917. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  81918. this._onAfterDrawPhaseObserver = null;
  81919. }
  81920. },
  81921. enumerable: true,
  81922. configurable: true
  81923. });
  81924. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  81925. /**
  81926. * Gets the perf counter used for draw calls
  81927. */
  81928. get: function () {
  81929. return this.scene.getEngine()._drawCalls;
  81930. },
  81931. enumerable: true,
  81932. configurable: true
  81933. });
  81934. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  81935. /**
  81936. * Gets the perf counter used for texture collisions
  81937. */
  81938. get: function () {
  81939. return this.scene.getEngine()._textureCollisions;
  81940. },
  81941. enumerable: true,
  81942. configurable: true
  81943. });
  81944. SceneInstrumentation.prototype.dispose = function () {
  81945. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  81946. this._onAfterRenderObserver = null;
  81947. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  81948. this._onBeforeActiveMeshesEvaluationObserver = null;
  81949. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  81950. this._onAfterActiveMeshesEvaluationObserver = null;
  81951. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  81952. this._onBeforeRenderTargetsRenderObserver = null;
  81953. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  81954. this._onAfterRenderTargetsRenderObserver = null;
  81955. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  81956. this._onBeforeAnimationsObserver = null;
  81957. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  81958. this._onBeforeParticlesRenderingObserver = null;
  81959. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  81960. this._onAfterParticlesRenderingObserver = null;
  81961. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  81962. this._onBeforeSpritesRenderingObserver = null;
  81963. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  81964. this._onAfterSpritesRenderingObserver = null;
  81965. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  81966. this._onBeforeDrawPhaseObserver = null;
  81967. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  81968. this._onAfterDrawPhaseObserver = null;
  81969. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  81970. this._onBeforePhysicsObserver = null;
  81971. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  81972. this._onAfterPhysicsObserver = null;
  81973. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  81974. this._onAfterAnimationsObserver = null;
  81975. this.scene = null;
  81976. };
  81977. return SceneInstrumentation;
  81978. }());
  81979. BABYLON.SceneInstrumentation = SceneInstrumentation;
  81980. })(BABYLON || (BABYLON = {}));
  81981. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  81982. var BABYLON;
  81983. (function (BABYLON) {
  81984. var _TimeToken = /** @class */ (function () {
  81985. function _TimeToken() {
  81986. this._timeElapsedQueryEnded = false;
  81987. }
  81988. return _TimeToken;
  81989. }());
  81990. BABYLON._TimeToken = _TimeToken;
  81991. })(BABYLON || (BABYLON = {}));
  81992. //# sourceMappingURL=babylon.timeToken.js.map
  81993. var BABYLON;
  81994. (function (BABYLON) {
  81995. /**
  81996. * Background material defines definition.
  81997. */
  81998. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  81999. __extends(BackgroundMaterialDefines, _super);
  82000. /**
  82001. * Constructor of the defines.
  82002. */
  82003. function BackgroundMaterialDefines() {
  82004. var _this = _super.call(this) || this;
  82005. /**
  82006. * True if the diffuse texture is in use.
  82007. */
  82008. _this.DIFFUSE = false;
  82009. /**
  82010. * The direct UV channel to use.
  82011. */
  82012. _this.DIFFUSEDIRECTUV = 0;
  82013. /**
  82014. * True if the diffuse texture is in gamma space.
  82015. */
  82016. _this.GAMMADIFFUSE = false;
  82017. /**
  82018. * True if the diffuse texture has opacity in the alpha channel.
  82019. */
  82020. _this.DIFFUSEHASALPHA = false;
  82021. /**
  82022. * True if you want the material to fade to transparent at grazing angle.
  82023. */
  82024. _this.OPACITYFRESNEL = false;
  82025. /**
  82026. * True if an extra blur needs to be added in the reflection.
  82027. */
  82028. _this.REFLECTIONBLUR = false;
  82029. /**
  82030. * True if you want the material to fade to reflection at grazing angle.
  82031. */
  82032. _this.REFLECTIONFRESNEL = false;
  82033. /**
  82034. * True if you want the material to falloff as far as you move away from the scene center.
  82035. */
  82036. _this.REFLECTIONFALLOFF = false;
  82037. /**
  82038. * False if the current Webgl implementation does not support the texture lod extension.
  82039. */
  82040. _this.TEXTURELODSUPPORT = false;
  82041. /**
  82042. * True to ensure the data are premultiplied.
  82043. */
  82044. _this.PREMULTIPLYALPHA = false;
  82045. /**
  82046. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  82047. */
  82048. _this.USERGBCOLOR = false;
  82049. /**
  82050. * True to add noise in order to reduce the banding effect.
  82051. */
  82052. _this.NOISE = false;
  82053. // Image Processing Configuration.
  82054. _this.IMAGEPROCESSING = false;
  82055. _this.VIGNETTE = false;
  82056. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  82057. _this.VIGNETTEBLENDMODEOPAQUE = false;
  82058. _this.TONEMAPPING = false;
  82059. _this.CONTRAST = false;
  82060. _this.COLORCURVES = false;
  82061. _this.COLORGRADING = false;
  82062. _this.COLORGRADING3D = false;
  82063. _this.SAMPLER3DGREENDEPTH = false;
  82064. _this.SAMPLER3DBGRMAP = false;
  82065. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  82066. _this.EXPOSURE = false;
  82067. // Reflection.
  82068. _this.REFLECTION = false;
  82069. _this.REFLECTIONMAP_3D = false;
  82070. _this.REFLECTIONMAP_SPHERICAL = false;
  82071. _this.REFLECTIONMAP_PLANAR = false;
  82072. _this.REFLECTIONMAP_CUBIC = false;
  82073. _this.REFLECTIONMAP_PROJECTION = false;
  82074. _this.REFLECTIONMAP_SKYBOX = false;
  82075. _this.REFLECTIONMAP_EXPLICIT = false;
  82076. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82077. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82078. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82079. _this.INVERTCUBICMAP = false;
  82080. _this.REFLECTIONMAP_OPPOSITEZ = false;
  82081. _this.LODINREFLECTIONALPHA = false;
  82082. _this.GAMMAREFLECTION = false;
  82083. // Default BJS.
  82084. _this.MAINUV1 = false;
  82085. _this.MAINUV2 = false;
  82086. _this.UV1 = false;
  82087. _this.UV2 = false;
  82088. _this.CLIPPLANE = false;
  82089. _this.POINTSIZE = false;
  82090. _this.FOG = false;
  82091. _this.NORMAL = false;
  82092. _this.NUM_BONE_INFLUENCERS = 0;
  82093. _this.BonesPerMesh = 0;
  82094. _this.INSTANCES = false;
  82095. _this.SHADOWFLOAT = false;
  82096. _this.rebuild();
  82097. return _this;
  82098. }
  82099. return BackgroundMaterialDefines;
  82100. }(BABYLON.MaterialDefines));
  82101. /**
  82102. * Background material used to create an efficient environement around your scene.
  82103. */
  82104. var BackgroundMaterial = /** @class */ (function (_super) {
  82105. __extends(BackgroundMaterial, _super);
  82106. /**
  82107. * constructor
  82108. * @param name The name of the material
  82109. * @param scene The scene to add the material to
  82110. */
  82111. function BackgroundMaterial(name, scene) {
  82112. var _this = _super.call(this, name, scene) || this;
  82113. _this.primaryColor = BABYLON.Color3.White();
  82114. _this.primaryLevel = 1;
  82115. _this.secondaryColor = BABYLON.Color3.Gray();
  82116. _this.secondaryLevel = 1;
  82117. _this.tertiaryColor = BABYLON.Color3.Black();
  82118. _this.tertiaryLevel = 1;
  82119. _this.reflectionTexture = null;
  82120. _this.reflectionBlur = 0;
  82121. _this.diffuseTexture = null;
  82122. /**
  82123. * Specify the list of lights casting shadow on the material.
  82124. * All scene shadow lights will be included if null.
  82125. */
  82126. _this._shadowLights = null;
  82127. _this.shadowLights = null;
  82128. _this.shadowBlurScale = 1;
  82129. _this.shadowLevel = 0;
  82130. _this.sceneCenter = BABYLON.Vector3.Zero();
  82131. _this.opacityFresnel = true;
  82132. _this.reflectionFresnel = false;
  82133. _this.reflectionFalloffDistance = 0.0;
  82134. _this.reflectionAmount = 1.0;
  82135. _this.reflectionReflectance0 = 0.05;
  82136. _this.reflectionReflectance90 = 0.5;
  82137. _this.useRGBColor = true;
  82138. _this.enableNoise = false;
  82139. /**
  82140. * Number of Simultaneous lights allowed on the material.
  82141. */
  82142. _this._maxSimultaneousLights = 4;
  82143. _this.maxSimultaneousLights = 4;
  82144. /**
  82145. * Keep track of the image processing observer to allow dispose and replace.
  82146. */
  82147. _this._imageProcessingObserver = null;
  82148. // Temp values kept as cache in the material.
  82149. _this._renderTargets = new BABYLON.SmartArray(16);
  82150. _this._reflectionControls = BABYLON.Vector4.Zero();
  82151. // Setup the default processing configuration to the scene.
  82152. _this._attachImageProcessingConfiguration(null);
  82153. _this.getRenderTargetTextures = function () {
  82154. _this._renderTargets.reset();
  82155. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  82156. _this._renderTargets.push(_this._diffuseTexture);
  82157. }
  82158. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  82159. _this._renderTargets.push(_this._reflectionTexture);
  82160. }
  82161. return _this._renderTargets;
  82162. };
  82163. return _this;
  82164. }
  82165. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  82166. /**
  82167. * Sets the reflection reflectance fresnel values according to the default standard
  82168. * empirically know to work well :-)
  82169. */
  82170. set: function (value) {
  82171. var reflectionWeight = value;
  82172. if (reflectionWeight < 0.5) {
  82173. reflectionWeight = reflectionWeight * 2.0;
  82174. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  82175. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  82176. }
  82177. else {
  82178. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  82179. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  82180. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  82181. }
  82182. },
  82183. enumerable: true,
  82184. configurable: true
  82185. });
  82186. /**
  82187. * Attaches a new image processing configuration to the PBR Material.
  82188. * @param configuration (if null the scene configuration will be use)
  82189. */
  82190. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  82191. var _this = this;
  82192. if (configuration === this._imageProcessingConfiguration) {
  82193. return;
  82194. }
  82195. // Detaches observer.
  82196. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82197. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82198. }
  82199. // Pick the scene configuration if needed.
  82200. if (!configuration) {
  82201. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  82202. }
  82203. else {
  82204. this._imageProcessingConfiguration = configuration;
  82205. }
  82206. // Attaches observer.
  82207. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  82208. _this._markAllSubMeshesAsImageProcessingDirty();
  82209. });
  82210. };
  82211. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  82212. /**
  82213. * Gets the image processing configuration used either in this material.
  82214. */
  82215. get: function () {
  82216. return this._imageProcessingConfiguration;
  82217. },
  82218. /**
  82219. * Sets the Default image processing configuration used either in the this material.
  82220. *
  82221. * If sets to null, the scene one is in use.
  82222. */
  82223. set: function (value) {
  82224. this._attachImageProcessingConfiguration(value);
  82225. // Ensure the effect will be rebuilt.
  82226. this._markAllSubMeshesAsTexturesDirty();
  82227. },
  82228. enumerable: true,
  82229. configurable: true
  82230. });
  82231. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  82232. /**
  82233. * Gets wether the color curves effect is enabled.
  82234. */
  82235. get: function () {
  82236. return this.imageProcessingConfiguration.colorCurvesEnabled;
  82237. },
  82238. /**
  82239. * Sets wether the color curves effect is enabled.
  82240. */
  82241. set: function (value) {
  82242. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  82243. },
  82244. enumerable: true,
  82245. configurable: true
  82246. });
  82247. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  82248. /**
  82249. * Gets wether the color grading effect is enabled.
  82250. */
  82251. get: function () {
  82252. return this.imageProcessingConfiguration.colorGradingEnabled;
  82253. },
  82254. /**
  82255. * Gets wether the color grading effect is enabled.
  82256. */
  82257. set: function (value) {
  82258. this.imageProcessingConfiguration.colorGradingEnabled = value;
  82259. },
  82260. enumerable: true,
  82261. configurable: true
  82262. });
  82263. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  82264. /**
  82265. * Gets wether tonemapping is enabled or not.
  82266. */
  82267. get: function () {
  82268. return this._imageProcessingConfiguration.toneMappingEnabled;
  82269. },
  82270. /**
  82271. * Sets wether tonemapping is enabled or not
  82272. */
  82273. set: function (value) {
  82274. this._imageProcessingConfiguration.toneMappingEnabled = value;
  82275. },
  82276. enumerable: true,
  82277. configurable: true
  82278. });
  82279. ;
  82280. ;
  82281. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  82282. /**
  82283. * The camera exposure used on this material.
  82284. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82285. * This corresponds to a photographic exposure.
  82286. */
  82287. get: function () {
  82288. return this._imageProcessingConfiguration.exposure;
  82289. },
  82290. /**
  82291. * The camera exposure used on this material.
  82292. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  82293. * This corresponds to a photographic exposure.
  82294. */
  82295. set: function (value) {
  82296. this._imageProcessingConfiguration.exposure = value;
  82297. },
  82298. enumerable: true,
  82299. configurable: true
  82300. });
  82301. ;
  82302. ;
  82303. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  82304. /**
  82305. * Gets The camera contrast used on this material.
  82306. */
  82307. get: function () {
  82308. return this._imageProcessingConfiguration.contrast;
  82309. },
  82310. /**
  82311. * Sets The camera contrast used on this material.
  82312. */
  82313. set: function (value) {
  82314. this._imageProcessingConfiguration.contrast = value;
  82315. },
  82316. enumerable: true,
  82317. configurable: true
  82318. });
  82319. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  82320. /**
  82321. * Gets the Color Grading 2D Lookup Texture.
  82322. */
  82323. get: function () {
  82324. return this._imageProcessingConfiguration.colorGradingTexture;
  82325. },
  82326. /**
  82327. * Sets the Color Grading 2D Lookup Texture.
  82328. */
  82329. set: function (value) {
  82330. this.imageProcessingConfiguration.colorGradingTexture = value;
  82331. },
  82332. enumerable: true,
  82333. configurable: true
  82334. });
  82335. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  82336. /**
  82337. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82338. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82339. * 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;
  82340. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82341. */
  82342. get: function () {
  82343. return this.imageProcessingConfiguration.colorCurves;
  82344. },
  82345. /**
  82346. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  82347. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  82348. * 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;
  82349. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  82350. */
  82351. set: function (value) {
  82352. this.imageProcessingConfiguration.colorCurves = value;
  82353. },
  82354. enumerable: true,
  82355. configurable: true
  82356. });
  82357. /**
  82358. * The entire material has been created in order to prevent overdraw.
  82359. * @returns false
  82360. */
  82361. BackgroundMaterial.prototype.needAlphaTesting = function () {
  82362. return true;
  82363. };
  82364. /**
  82365. * The entire material has been created in order to prevent overdraw.
  82366. * @returns true if blending is enable
  82367. */
  82368. BackgroundMaterial.prototype.needAlphaBlending = function () {
  82369. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  82370. };
  82371. /**
  82372. * Checks wether the material is ready to be rendered for a given mesh.
  82373. * @param mesh The mesh to render
  82374. * @param subMesh The submesh to check against
  82375. * @param useInstances Specify wether or not the material is used with instances
  82376. */
  82377. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  82378. var _this = this;
  82379. if (useInstances === void 0) { useInstances = false; }
  82380. if (subMesh.effect && this.isFrozen) {
  82381. if (this._wasPreviouslyReady) {
  82382. return true;
  82383. }
  82384. }
  82385. if (!subMesh._materialDefines) {
  82386. subMesh._materialDefines = new BackgroundMaterialDefines();
  82387. }
  82388. var scene = this.getScene();
  82389. var defines = subMesh._materialDefines;
  82390. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  82391. if (defines._renderId === scene.getRenderId()) {
  82392. return true;
  82393. }
  82394. }
  82395. var engine = scene.getEngine();
  82396. // Lights
  82397. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  82398. defines._needNormals = true;
  82399. // Textures
  82400. if (defines._areTexturesDirty) {
  82401. defines._needUVs = false;
  82402. if (scene.texturesEnabled) {
  82403. if (scene.getEngine().getCaps().textureLOD) {
  82404. defines.TEXTURELODSUPPORT = true;
  82405. }
  82406. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82407. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  82408. return false;
  82409. }
  82410. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  82411. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  82412. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  82413. defines.OPACITYFRESNEL = this._opacityFresnel;
  82414. }
  82415. else {
  82416. defines.DIFFUSE = false;
  82417. defines.DIFFUSEHASALPHA = false;
  82418. defines.GAMMADIFFUSE = false;
  82419. defines.OPACITYFRESNEL = false;
  82420. }
  82421. var reflectionTexture = this._reflectionTexture;
  82422. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82423. if (!reflectionTexture.isReadyOrNotBlocking()) {
  82424. return false;
  82425. }
  82426. defines.REFLECTION = true;
  82427. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  82428. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  82429. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  82430. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  82431. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  82432. defines.INVERTCUBICMAP = true;
  82433. }
  82434. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  82435. switch (reflectionTexture.coordinatesMode) {
  82436. case BABYLON.Texture.CUBIC_MODE:
  82437. case BABYLON.Texture.INVCUBIC_MODE:
  82438. defines.REFLECTIONMAP_CUBIC = true;
  82439. break;
  82440. case BABYLON.Texture.EXPLICIT_MODE:
  82441. defines.REFLECTIONMAP_EXPLICIT = true;
  82442. break;
  82443. case BABYLON.Texture.PLANAR_MODE:
  82444. defines.REFLECTIONMAP_PLANAR = true;
  82445. break;
  82446. case BABYLON.Texture.PROJECTION_MODE:
  82447. defines.REFLECTIONMAP_PROJECTION = true;
  82448. break;
  82449. case BABYLON.Texture.SKYBOX_MODE:
  82450. defines.REFLECTIONMAP_SKYBOX = true;
  82451. break;
  82452. case BABYLON.Texture.SPHERICAL_MODE:
  82453. defines.REFLECTIONMAP_SPHERICAL = true;
  82454. break;
  82455. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  82456. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  82457. break;
  82458. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  82459. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  82460. break;
  82461. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  82462. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  82463. break;
  82464. }
  82465. if (this.reflectionFresnel) {
  82466. defines.REFLECTIONFRESNEL = true;
  82467. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  82468. this._reflectionControls.x = this.reflectionAmount;
  82469. this._reflectionControls.y = this.reflectionReflectance0;
  82470. this._reflectionControls.z = this.reflectionReflectance90;
  82471. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  82472. }
  82473. else {
  82474. defines.REFLECTIONFRESNEL = false;
  82475. defines.REFLECTIONFALLOFF = false;
  82476. }
  82477. }
  82478. else {
  82479. defines.REFLECTION = false;
  82480. defines.REFLECTIONFALLOFF = false;
  82481. defines.REFLECTIONBLUR = false;
  82482. defines.REFLECTIONMAP_3D = false;
  82483. defines.REFLECTIONMAP_SPHERICAL = false;
  82484. defines.REFLECTIONMAP_PLANAR = false;
  82485. defines.REFLECTIONMAP_CUBIC = false;
  82486. defines.REFLECTIONMAP_PROJECTION = false;
  82487. defines.REFLECTIONMAP_SKYBOX = false;
  82488. defines.REFLECTIONMAP_EXPLICIT = false;
  82489. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  82490. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  82491. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  82492. defines.INVERTCUBICMAP = false;
  82493. defines.REFLECTIONMAP_OPPOSITEZ = false;
  82494. defines.LODINREFLECTIONALPHA = false;
  82495. defines.GAMMAREFLECTION = false;
  82496. }
  82497. }
  82498. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  82499. defines.USERGBCOLOR = this._useRGBColor;
  82500. defines.NOISE = this._enableNoise;
  82501. }
  82502. if (defines._areImageProcessingDirty) {
  82503. if (!this._imageProcessingConfiguration.isReady()) {
  82504. return false;
  82505. }
  82506. this._imageProcessingConfiguration.prepareDefines(defines);
  82507. }
  82508. // Misc.
  82509. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  82510. // Values that need to be evaluated on every frame
  82511. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  82512. // Attribs
  82513. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  82514. if (mesh) {
  82515. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  82516. mesh.createNormals(true);
  82517. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  82518. }
  82519. }
  82520. }
  82521. // Get correct effect
  82522. if (defines.isDirty) {
  82523. defines.markAsProcessed();
  82524. scene.resetCachedMaterial();
  82525. // Fallbacks
  82526. var fallbacks = new BABYLON.EffectFallbacks();
  82527. if (defines.FOG) {
  82528. fallbacks.addFallback(0, "FOG");
  82529. }
  82530. if (defines.POINTSIZE) {
  82531. fallbacks.addFallback(1, "POINTSIZE");
  82532. }
  82533. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  82534. if (defines.NUM_BONE_INFLUENCERS > 0) {
  82535. fallbacks.addCPUSkinningFallback(0, mesh);
  82536. }
  82537. //Attributes
  82538. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82539. if (defines.NORMAL) {
  82540. attribs.push(BABYLON.VertexBuffer.NormalKind);
  82541. }
  82542. if (defines.UV1) {
  82543. attribs.push(BABYLON.VertexBuffer.UVKind);
  82544. }
  82545. if (defines.UV2) {
  82546. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82547. }
  82548. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  82549. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  82550. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  82551. "vFogInfos", "vFogColor", "pointSize",
  82552. "vClipPlane", "mBones",
  82553. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  82554. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  82555. "shadowLevel", "alpha",
  82556. "vBackgroundCenter", "vReflectionControl",
  82557. "vDiffuseInfos", "diffuseMatrix",
  82558. ];
  82559. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  82560. var uniformBuffers = ["Material", "Scene"];
  82561. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  82562. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  82563. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  82564. uniformsNames: uniforms,
  82565. uniformBuffersNames: uniformBuffers,
  82566. samplers: samplers,
  82567. defines: defines,
  82568. maxSimultaneousLights: this._maxSimultaneousLights
  82569. });
  82570. var onCompiled = function (effect) {
  82571. if (_this.onCompiled) {
  82572. _this.onCompiled(effect);
  82573. }
  82574. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  82575. };
  82576. var join = defines.toString();
  82577. subMesh.setEffect(scene.getEngine().createEffect("background", {
  82578. attributes: attribs,
  82579. uniformsNames: uniforms,
  82580. uniformBuffersNames: uniformBuffers,
  82581. samplers: samplers,
  82582. defines: join,
  82583. fallbacks: fallbacks,
  82584. onCompiled: onCompiled,
  82585. onError: this.onError,
  82586. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  82587. }, engine), defines);
  82588. this.buildUniformLayout();
  82589. }
  82590. if (!subMesh.effect || !subMesh.effect.isReady()) {
  82591. return false;
  82592. }
  82593. defines._renderId = scene.getRenderId();
  82594. this._wasPreviouslyReady = true;
  82595. return true;
  82596. };
  82597. /**
  82598. * Build the uniform buffer used in the material.
  82599. */
  82600. BackgroundMaterial.prototype.buildUniformLayout = function () {
  82601. // Order is important !
  82602. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  82603. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  82604. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  82605. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  82606. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  82607. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  82608. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  82609. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  82610. this._uniformBuffer.addUniform("pointSize", 1);
  82611. this._uniformBuffer.addUniform("shadowLevel", 1);
  82612. this._uniformBuffer.addUniform("alpha", 1);
  82613. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  82614. this._uniformBuffer.addUniform("vReflectionControl", 4);
  82615. this._uniformBuffer.create();
  82616. };
  82617. /**
  82618. * Unbind the material.
  82619. */
  82620. BackgroundMaterial.prototype.unbind = function () {
  82621. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  82622. this._uniformBuffer.setTexture("diffuseSampler", null);
  82623. }
  82624. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  82625. this._uniformBuffer.setTexture("reflectionSampler", null);
  82626. }
  82627. _super.prototype.unbind.call(this);
  82628. };
  82629. /**
  82630. * Bind only the world matrix to the material.
  82631. * @param world The world matrix to bind.
  82632. */
  82633. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  82634. this._activeEffect.setMatrix("world", world);
  82635. };
  82636. /**
  82637. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  82638. * @param world The world matrix to bind.
  82639. * @param subMesh The submesh to bind for.
  82640. */
  82641. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  82642. var scene = this.getScene();
  82643. var defines = subMesh._materialDefines;
  82644. if (!defines) {
  82645. return;
  82646. }
  82647. var effect = subMesh.effect;
  82648. if (!effect) {
  82649. return;
  82650. }
  82651. this._activeEffect = effect;
  82652. // Matrices
  82653. this.bindOnlyWorldMatrix(world);
  82654. // Bones
  82655. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  82656. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  82657. if (mustRebind) {
  82658. this._uniformBuffer.bindToEffect(effect, "Material");
  82659. this.bindViewProjection(effect);
  82660. var reflectionTexture = this._reflectionTexture;
  82661. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  82662. // Texture uniforms
  82663. if (scene.texturesEnabled) {
  82664. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82665. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  82666. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  82667. }
  82668. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82669. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  82670. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  82671. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  82672. }
  82673. }
  82674. if (this.shadowLevel > 0) {
  82675. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  82676. }
  82677. this._uniformBuffer.updateFloat("alpha", this.alpha);
  82678. // Point size
  82679. if (this.pointsCloud) {
  82680. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  82681. }
  82682. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  82683. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  82684. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  82685. }
  82686. // Textures
  82687. if (scene.texturesEnabled) {
  82688. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  82689. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  82690. }
  82691. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  82692. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  82693. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  82694. }
  82695. else if (!defines.REFLECTIONBLUR) {
  82696. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  82697. }
  82698. else {
  82699. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  82700. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  82701. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  82702. }
  82703. if (defines.REFLECTIONFRESNEL) {
  82704. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  82705. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  82706. }
  82707. }
  82708. }
  82709. // Clip plane
  82710. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  82711. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  82712. }
  82713. if (mustRebind || !this.isFrozen) {
  82714. if (scene.lightsEnabled) {
  82715. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  82716. }
  82717. // View
  82718. this.bindView(effect);
  82719. // Fog
  82720. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  82721. // image processing
  82722. this._imageProcessingConfiguration.bind(this._activeEffect);
  82723. }
  82724. this._uniformBuffer.update();
  82725. this._afterBind(mesh);
  82726. };
  82727. /**
  82728. * Dispose the material.
  82729. * @forceDisposeEffect Force disposal of the associated effect.
  82730. * @forceDisposeTextures Force disposal of the associated textures.
  82731. */
  82732. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  82733. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  82734. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  82735. if (forceDisposeTextures) {
  82736. if (this.diffuseTexture) {
  82737. this.diffuseTexture.dispose();
  82738. }
  82739. if (this.reflectionTexture) {
  82740. this.reflectionTexture.dispose();
  82741. }
  82742. }
  82743. this._renderTargets.dispose();
  82744. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82745. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82746. }
  82747. _super.prototype.dispose.call(this, forceDisposeEffect);
  82748. };
  82749. /**
  82750. * Clones the material.
  82751. * @name The cloned name.
  82752. * @returns The cloned material.
  82753. */
  82754. BackgroundMaterial.prototype.clone = function (name) {
  82755. var _this = this;
  82756. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  82757. };
  82758. /**
  82759. * Serializes the current material to its JSON representation.
  82760. * @returns The JSON representation.
  82761. */
  82762. BackgroundMaterial.prototype.serialize = function () {
  82763. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  82764. serializationObject.customType = "BABYLON.BackgroundMaterial";
  82765. return serializationObject;
  82766. };
  82767. /**
  82768. * Gets the class name of the material
  82769. * @returns "BackgroundMaterial"
  82770. */
  82771. BackgroundMaterial.prototype.getClassName = function () {
  82772. return "BackgroundMaterial";
  82773. };
  82774. /**
  82775. * Parse a JSON input to create back a background material.
  82776. * @param source
  82777. * @param scene
  82778. * @param rootUrl
  82779. * @returns the instantiated BackgroundMaterial.
  82780. */
  82781. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  82782. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  82783. };
  82784. /**
  82785. * Standard reflectance value at parallel view angle.
  82786. */
  82787. BackgroundMaterial.standardReflectance0 = 0.05;
  82788. /**
  82789. * Standard reflectance value at grazing angle.
  82790. */
  82791. BackgroundMaterial.standardReflectance90 = 0.5;
  82792. __decorate([
  82793. BABYLON.serializeAsColor3()
  82794. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  82795. __decorate([
  82796. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  82797. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  82798. __decorate([
  82799. BABYLON.serialize()
  82800. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  82801. __decorate([
  82802. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  82803. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  82804. __decorate([
  82805. BABYLON.serializeAsColor3()
  82806. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  82807. __decorate([
  82808. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  82809. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  82810. __decorate([
  82811. BABYLON.serialize()
  82812. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  82813. __decorate([
  82814. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  82815. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  82816. __decorate([
  82817. BABYLON.serializeAsColor3()
  82818. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  82819. __decorate([
  82820. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  82821. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  82822. __decorate([
  82823. BABYLON.serialize()
  82824. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  82825. __decorate([
  82826. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  82827. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  82828. __decorate([
  82829. BABYLON.serializeAsTexture()
  82830. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  82831. __decorate([
  82832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82833. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  82834. __decorate([
  82835. BABYLON.serialize()
  82836. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  82837. __decorate([
  82838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82839. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  82840. __decorate([
  82841. BABYLON.serializeAsTexture()
  82842. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  82843. __decorate([
  82844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82845. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  82846. __decorate([
  82847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82848. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  82849. __decorate([
  82850. BABYLON.serialize()
  82851. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  82852. __decorate([
  82853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82854. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  82855. __decorate([
  82856. BABYLON.serialize()
  82857. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  82858. __decorate([
  82859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82860. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  82861. __decorate([
  82862. BABYLON.serializeAsVector3()
  82863. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  82864. __decorate([
  82865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82866. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  82867. __decorate([
  82868. BABYLON.serialize()
  82869. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  82870. __decorate([
  82871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82872. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  82873. __decorate([
  82874. BABYLON.serialize()
  82875. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  82876. __decorate([
  82877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82878. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  82879. __decorate([
  82880. BABYLON.serialize()
  82881. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  82882. __decorate([
  82883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82884. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  82885. __decorate([
  82886. BABYLON.serialize()
  82887. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  82888. __decorate([
  82889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82890. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  82891. __decorate([
  82892. BABYLON.serialize()
  82893. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  82894. __decorate([
  82895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82896. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  82897. __decorate([
  82898. BABYLON.serialize()
  82899. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  82900. __decorate([
  82901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82902. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  82903. __decorate([
  82904. BABYLON.serialize()
  82905. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  82906. __decorate([
  82907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82908. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  82909. __decorate([
  82910. BABYLON.serialize()
  82911. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  82912. __decorate([
  82913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82914. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  82915. __decorate([
  82916. BABYLON.serialize()
  82917. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  82918. __decorate([
  82919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  82920. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  82921. __decorate([
  82922. BABYLON.serializeAsImageProcessingConfiguration()
  82923. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  82924. return BackgroundMaterial;
  82925. }(BABYLON.PushMaterial));
  82926. BABYLON.BackgroundMaterial = BackgroundMaterial;
  82927. })(BABYLON || (BABYLON = {}));
  82928. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  82929. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82930. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82931. s = arguments[i];
  82932. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82933. t[p] = s[p];
  82934. }
  82935. return t;
  82936. };
  82937. var BABYLON;
  82938. (function (BABYLON) {
  82939. /**
  82940. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  82941. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  82942. * It also helps with the default setup of your imageProcessing configuration.
  82943. */
  82944. var EnvironmentHelper = /** @class */ (function () {
  82945. /**
  82946. * constructor
  82947. * @param options
  82948. * @param scene The scene to add the material to
  82949. */
  82950. function EnvironmentHelper(options, scene) {
  82951. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  82952. this._scene = scene;
  82953. this._setupBackground();
  82954. this._setupImageProcessing();
  82955. }
  82956. /**
  82957. * Creates the default options for the helper.
  82958. */
  82959. EnvironmentHelper._getDefaultOptions = function () {
  82960. return {
  82961. createGround: true,
  82962. groundSize: 15,
  82963. groundTexture: this._groundTextureCDNUrl,
  82964. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  82965. groundOpacity: 0.9,
  82966. enableGroundShadow: true,
  82967. groundShadowLevel: 0.5,
  82968. enableGroundMirror: false,
  82969. groundMirrorSizeRatio: 0.3,
  82970. groundMirrorBlurKernel: 64,
  82971. groundMirrorAmount: 1,
  82972. groundMirrorFresnelWeight: 1,
  82973. groundMirrorFallOffDistance: 0,
  82974. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  82975. groundYBias: 0.00001,
  82976. createSkybox: true,
  82977. skyboxSize: 20,
  82978. skyboxTexture: this._skyboxTextureCDNUrl,
  82979. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  82980. backgroundYRotation: 0,
  82981. sizeAuto: true,
  82982. rootPosition: BABYLON.Vector3.Zero(),
  82983. setupImageProcessing: true,
  82984. environmentTexture: this._environmentTextureCDNUrl,
  82985. cameraExposure: 0.8,
  82986. cameraContrast: 1.2,
  82987. toneMappingEnabled: true,
  82988. };
  82989. };
  82990. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  82991. /**
  82992. * Gets the root mesh created by the helper.
  82993. */
  82994. get: function () {
  82995. return this._rootMesh;
  82996. },
  82997. enumerable: true,
  82998. configurable: true
  82999. });
  83000. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  83001. /**
  83002. * Gets the skybox created by the helper.
  83003. */
  83004. get: function () {
  83005. return this._skybox;
  83006. },
  83007. enumerable: true,
  83008. configurable: true
  83009. });
  83010. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  83011. /**
  83012. * Gets the skybox texture created by the helper.
  83013. */
  83014. get: function () {
  83015. return this._skyboxTexture;
  83016. },
  83017. enumerable: true,
  83018. configurable: true
  83019. });
  83020. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  83021. /**
  83022. * Gets the skybox material created by the helper.
  83023. */
  83024. get: function () {
  83025. return this._skyboxMaterial;
  83026. },
  83027. enumerable: true,
  83028. configurable: true
  83029. });
  83030. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  83031. /**
  83032. * Gets the ground mesh created by the helper.
  83033. */
  83034. get: function () {
  83035. return this._ground;
  83036. },
  83037. enumerable: true,
  83038. configurable: true
  83039. });
  83040. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  83041. /**
  83042. * Gets the ground texture created by the helper.
  83043. */
  83044. get: function () {
  83045. return this._groundTexture;
  83046. },
  83047. enumerable: true,
  83048. configurable: true
  83049. });
  83050. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  83051. /**
  83052. * Gets the ground mirror created by the helper.
  83053. */
  83054. get: function () {
  83055. return this._groundMirror;
  83056. },
  83057. enumerable: true,
  83058. configurable: true
  83059. });
  83060. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  83061. /**
  83062. * Gets the ground mirror render list to helps pushing the meshes
  83063. * you wish in the ground reflection.
  83064. */
  83065. get: function () {
  83066. if (this._groundMirror) {
  83067. return this._groundMirror.renderList;
  83068. }
  83069. return null;
  83070. },
  83071. enumerable: true,
  83072. configurable: true
  83073. });
  83074. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  83075. /**
  83076. * Gets the ground material created by the helper.
  83077. */
  83078. get: function () {
  83079. return this._groundMaterial;
  83080. },
  83081. enumerable: true,
  83082. configurable: true
  83083. });
  83084. /**
  83085. * Updates the background according to the new options
  83086. * @param options
  83087. */
  83088. EnvironmentHelper.prototype.updateOptions = function (options) {
  83089. var newOptions = __assign({}, this._options, options);
  83090. if (this._ground && !newOptions.createGround) {
  83091. this._ground.dispose();
  83092. this._ground = null;
  83093. }
  83094. if (this._groundMaterial && !newOptions.createGround) {
  83095. this._groundMaterial.dispose();
  83096. this._groundMaterial = null;
  83097. }
  83098. if (this._groundTexture) {
  83099. if (this._options.groundTexture != newOptions.groundTexture) {
  83100. this._groundTexture.dispose();
  83101. this._groundTexture = null;
  83102. }
  83103. }
  83104. if (this._skybox && !newOptions.createSkybox) {
  83105. this._skybox.dispose();
  83106. this._skybox = null;
  83107. }
  83108. if (this._skyboxMaterial && !newOptions.createSkybox) {
  83109. this._skyboxMaterial.dispose();
  83110. this._skyboxMaterial = null;
  83111. }
  83112. if (this._skyboxTexture) {
  83113. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  83114. this._skyboxTexture.dispose();
  83115. this._skyboxTexture = null;
  83116. }
  83117. }
  83118. if (this._groundMirror && !newOptions.enableGroundMirror) {
  83119. this._groundMirror.dispose();
  83120. this._groundMirror = null;
  83121. }
  83122. if (this._scene.environmentTexture) {
  83123. if (this._options.environmentTexture != newOptions.environmentTexture) {
  83124. this._scene.environmentTexture.dispose();
  83125. }
  83126. }
  83127. this._options = newOptions;
  83128. this._setupBackground();
  83129. this._setupImageProcessing();
  83130. };
  83131. /**
  83132. * Sets the primary color of all the available elements.
  83133. * @param color
  83134. */
  83135. EnvironmentHelper.prototype.setMainColor = function (color) {
  83136. if (this.groundMaterial) {
  83137. this.groundMaterial.primaryColor = color;
  83138. }
  83139. if (this.skyboxMaterial) {
  83140. this.skyboxMaterial.primaryColor = color;
  83141. }
  83142. if (this.groundMirror) {
  83143. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  83144. }
  83145. };
  83146. /**
  83147. * Setup the image processing according to the specified options.
  83148. */
  83149. EnvironmentHelper.prototype._setupImageProcessing = function () {
  83150. if (this._options.setupImageProcessing) {
  83151. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  83152. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  83153. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  83154. this._setupEnvironmentTexture();
  83155. }
  83156. };
  83157. /**
  83158. * Setup the environment texture according to the specified options.
  83159. */
  83160. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  83161. if (this._scene.environmentTexture) {
  83162. return;
  83163. }
  83164. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  83165. this._scene.environmentTexture = this._options.environmentTexture;
  83166. return;
  83167. }
  83168. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  83169. this._scene.environmentTexture = environmentTexture;
  83170. };
  83171. /**
  83172. * Setup the background according to the specified options.
  83173. */
  83174. EnvironmentHelper.prototype._setupBackground = function () {
  83175. if (!this._rootMesh) {
  83176. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  83177. }
  83178. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  83179. var sceneSize = this._getSceneSize();
  83180. if (this._options.createGround) {
  83181. this._setupGround(sceneSize);
  83182. this._setupGroundMaterial();
  83183. this._setupGroundDiffuseTexture();
  83184. if (this._options.enableGroundMirror) {
  83185. this._setupGroundMirrorTexture(sceneSize);
  83186. }
  83187. this._setupMirrorInGroundMaterial();
  83188. }
  83189. if (this._options.createSkybox) {
  83190. this._setupSkybox(sceneSize);
  83191. this._setupSkyboxMaterial();
  83192. this._setupSkyboxReflectionTexture();
  83193. }
  83194. this._rootMesh.position.x = sceneSize.rootPosition.x;
  83195. this._rootMesh.position.z = sceneSize.rootPosition.z;
  83196. this._rootMesh.position.y = sceneSize.rootPosition.y;
  83197. };
  83198. /**
  83199. * Get the scene sizes according to the setup.
  83200. */
  83201. EnvironmentHelper.prototype._getSceneSize = function () {
  83202. var groundSize = this._options.groundSize;
  83203. var skyboxSize = this._options.skyboxSize;
  83204. var rootPosition = this._options.rootPosition;
  83205. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  83206. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83207. }
  83208. var sceneExtends = this._scene.getWorldExtends();
  83209. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  83210. if (this._options.sizeAuto) {
  83211. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  83212. this._scene.activeCamera.upperRadiusLimit) {
  83213. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  83214. skyboxSize = groundSize;
  83215. }
  83216. var sceneDiagonalLenght = sceneDiagonal.length();
  83217. if (sceneDiagonalLenght > groundSize) {
  83218. groundSize = sceneDiagonalLenght * 2;
  83219. skyboxSize = groundSize;
  83220. }
  83221. // 10 % bigger.
  83222. groundSize *= 1.1;
  83223. skyboxSize *= 1.5;
  83224. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  83225. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  83226. }
  83227. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  83228. };
  83229. /**
  83230. * Setup the ground according to the specified options.
  83231. */
  83232. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  83233. var _this = this;
  83234. if (!this._ground) {
  83235. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  83236. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  83237. this._ground.parent = this._rootMesh;
  83238. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  83239. }
  83240. this._ground.receiveShadows = this._options.enableGroundShadow;
  83241. };
  83242. /**
  83243. * Setup the ground material according to the specified options.
  83244. */
  83245. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  83246. if (!this._groundMaterial) {
  83247. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  83248. }
  83249. this._groundMaterial.alpha = this._options.groundOpacity;
  83250. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  83251. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  83252. this._groundMaterial.primaryLevel = 1;
  83253. this._groundMaterial.primaryColor = this._options.groundColor;
  83254. this._groundMaterial.secondaryLevel = 0;
  83255. this._groundMaterial.tertiaryLevel = 0;
  83256. this._groundMaterial.useRGBColor = false;
  83257. this._groundMaterial.enableNoise = true;
  83258. if (this._ground) {
  83259. this._ground.material = this._groundMaterial;
  83260. }
  83261. };
  83262. /**
  83263. * Setup the ground diffuse texture according to the specified options.
  83264. */
  83265. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  83266. if (!this._groundMaterial) {
  83267. return;
  83268. }
  83269. if (this._groundTexture) {
  83270. return;
  83271. }
  83272. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  83273. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  83274. return;
  83275. }
  83276. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  83277. diffuseTexture.gammaSpace = false;
  83278. diffuseTexture.hasAlpha = true;
  83279. this._groundMaterial.diffuseTexture = diffuseTexture;
  83280. };
  83281. /**
  83282. * Setup the ground mirror texture according to the specified options.
  83283. */
  83284. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  83285. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83286. if (!this._groundMirror) {
  83287. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  83288. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  83289. this._groundMirror.anisotropicFilteringLevel = 1;
  83290. this._groundMirror.wrapU = wrapping;
  83291. this._groundMirror.wrapV = wrapping;
  83292. this._groundMirror.gammaSpace = false;
  83293. if (this._groundMirror.renderList) {
  83294. for (var i = 0; i < this._scene.meshes.length; i++) {
  83295. var mesh = this._scene.meshes[i];
  83296. if (mesh !== this._ground &&
  83297. mesh !== this._skybox &&
  83298. mesh !== this._rootMesh) {
  83299. this._groundMirror.renderList.push(mesh);
  83300. }
  83301. }
  83302. }
  83303. }
  83304. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  83305. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  83306. };
  83307. /**
  83308. * Setup the ground to receive the mirror texture.
  83309. */
  83310. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  83311. if (this._groundMaterial) {
  83312. this._groundMaterial.reflectionTexture = this._groundMirror;
  83313. this._groundMaterial.reflectionFresnel = true;
  83314. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  83315. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  83316. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  83317. }
  83318. };
  83319. /**
  83320. * Setup the skybox according to the specified options.
  83321. */
  83322. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  83323. var _this = this;
  83324. if (!this._skybox) {
  83325. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  83326. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  83327. }
  83328. this._skybox.parent = this._rootMesh;
  83329. };
  83330. /**
  83331. * Setup the skybox material according to the specified options.
  83332. */
  83333. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  83334. if (!this._skybox) {
  83335. return;
  83336. }
  83337. if (!this._skyboxMaterial) {
  83338. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  83339. }
  83340. this._skyboxMaterial.useRGBColor = false;
  83341. this._skyboxMaterial.primaryLevel = 1;
  83342. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  83343. this._skyboxMaterial.secondaryLevel = 0;
  83344. this._skyboxMaterial.tertiaryLevel = 0;
  83345. this._skyboxMaterial.enableNoise = true;
  83346. this._skybox.material = this._skyboxMaterial;
  83347. };
  83348. /**
  83349. * Setup the skybox reflection texture according to the specified options.
  83350. */
  83351. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  83352. if (!this._skyboxMaterial) {
  83353. return;
  83354. }
  83355. if (this._skyboxTexture) {
  83356. return;
  83357. }
  83358. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  83359. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83360. return;
  83361. }
  83362. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  83363. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  83364. this._skyboxTexture.gammaSpace = false;
  83365. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  83366. };
  83367. /**
  83368. * Dispose all the elements created by the Helper.
  83369. */
  83370. EnvironmentHelper.prototype.dispose = function () {
  83371. if (this._groundMaterial) {
  83372. this._groundMaterial.dispose(true, true);
  83373. }
  83374. if (this._skyboxMaterial) {
  83375. this._skyboxMaterial.dispose(true, true);
  83376. }
  83377. this._rootMesh.dispose(false);
  83378. };
  83379. /**
  83380. * Default ground texture URL.
  83381. */
  83382. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  83383. /**
  83384. * Default skybox texture URL.
  83385. */
  83386. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  83387. /**
  83388. * Default environment texture URL.
  83389. */
  83390. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  83391. return EnvironmentHelper;
  83392. }());
  83393. BABYLON.EnvironmentHelper = EnvironmentHelper;
  83394. })(BABYLON || (BABYLON = {}));
  83395. //# sourceMappingURL=babylon.environmentHelper.js.map
  83396. 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}","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#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 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}","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}"};
  83397. 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#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}\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 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#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 PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\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};"};
  83398. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  83399. var BABYLON;
  83400. (function (BABYLON) {
  83401. var GridMaterialDefines = /** @class */ (function (_super) {
  83402. __extends(GridMaterialDefines, _super);
  83403. function GridMaterialDefines() {
  83404. var _this = _super.call(this) || this;
  83405. _this.TRANSPARENT = false;
  83406. _this.FOG = false;
  83407. _this.PREMULTIPLYALPHA = false;
  83408. _this.rebuild();
  83409. return _this;
  83410. }
  83411. return GridMaterialDefines;
  83412. }(BABYLON.MaterialDefines));
  83413. /**
  83414. * The grid materials allows you to wrap any shape with a grid.
  83415. * Colors are customizable.
  83416. */
  83417. var GridMaterial = /** @class */ (function (_super) {
  83418. __extends(GridMaterial, _super);
  83419. /**
  83420. * constructor
  83421. * @param name The name given to the material in order to identify it afterwards.
  83422. * @param scene The scene the material is used in.
  83423. */
  83424. function GridMaterial(name, scene) {
  83425. var _this = _super.call(this, name, scene) || this;
  83426. /**
  83427. * Main color of the grid (e.g. between lines)
  83428. */
  83429. _this.mainColor = BABYLON.Color3.Black();
  83430. /**
  83431. * Color of the grid lines.
  83432. */
  83433. _this.lineColor = BABYLON.Color3.Teal();
  83434. /**
  83435. * The scale of the grid compared to unit.
  83436. */
  83437. _this.gridRatio = 1.0;
  83438. /**
  83439. * Allows setting an offset for the grid lines.
  83440. */
  83441. _this.gridOffset = BABYLON.Vector3.Zero();
  83442. /**
  83443. * The frequency of thicker lines.
  83444. */
  83445. _this.majorUnitFrequency = 10;
  83446. /**
  83447. * The visibility of minor units in the grid.
  83448. */
  83449. _this.minorUnitVisibility = 0.33;
  83450. /**
  83451. * The grid opacity outside of the lines.
  83452. */
  83453. _this.opacity = 1.0;
  83454. /**
  83455. * Determine RBG output is premultiplied by alpha value.
  83456. */
  83457. _this.preMultiplyAlpha = false;
  83458. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  83459. return _this;
  83460. }
  83461. /**
  83462. * Returns wehter or not the grid requires alpha blending.
  83463. */
  83464. GridMaterial.prototype.needAlphaBlending = function () {
  83465. return this.opacity < 1.0;
  83466. };
  83467. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  83468. return this.needAlphaBlending();
  83469. };
  83470. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83471. if (this.isFrozen) {
  83472. if (this._wasPreviouslyReady && subMesh.effect) {
  83473. return true;
  83474. }
  83475. }
  83476. if (!subMesh._materialDefines) {
  83477. subMesh._materialDefines = new GridMaterialDefines();
  83478. }
  83479. var defines = subMesh._materialDefines;
  83480. var scene = this.getScene();
  83481. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  83482. if (this._renderId === scene.getRenderId()) {
  83483. return true;
  83484. }
  83485. }
  83486. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  83487. defines.TRANSPARENT = !defines.TRANSPARENT;
  83488. defines.markAsUnprocessed();
  83489. }
  83490. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  83491. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  83492. defines.markAsUnprocessed();
  83493. }
  83494. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  83495. // Get correct effect
  83496. if (defines.isDirty) {
  83497. defines.markAsProcessed();
  83498. scene.resetCachedMaterial();
  83499. // Attributes
  83500. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83501. // Defines
  83502. var join = defines.toString();
  83503. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  83504. }
  83505. if (!subMesh.effect || !subMesh.effect.isReady()) {
  83506. return false;
  83507. }
  83508. this._renderId = scene.getRenderId();
  83509. this._wasPreviouslyReady = true;
  83510. return true;
  83511. };
  83512. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  83513. var scene = this.getScene();
  83514. var defines = subMesh._materialDefines;
  83515. if (!defines) {
  83516. return;
  83517. }
  83518. var effect = subMesh.effect;
  83519. if (!effect) {
  83520. return;
  83521. }
  83522. this._activeEffect = effect;
  83523. // Matrices
  83524. this.bindOnlyWorldMatrix(world);
  83525. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  83526. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  83527. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  83528. // Uniforms
  83529. if (this._mustRebind(scene, effect)) {
  83530. this._activeEffect.setColor3("mainColor", this.mainColor);
  83531. this._activeEffect.setColor3("lineColor", this.lineColor);
  83532. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  83533. this._gridControl.x = this.gridRatio;
  83534. this._gridControl.y = Math.round(this.majorUnitFrequency);
  83535. this._gridControl.z = this.minorUnitVisibility;
  83536. this._gridControl.w = this.opacity;
  83537. this._activeEffect.setVector4("gridControl", this._gridControl);
  83538. }
  83539. // Fog
  83540. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83541. this._afterBind(mesh, this._activeEffect);
  83542. };
  83543. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  83544. _super.prototype.dispose.call(this, forceDisposeEffect);
  83545. };
  83546. GridMaterial.prototype.clone = function (name) {
  83547. var _this = this;
  83548. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  83549. };
  83550. GridMaterial.prototype.serialize = function () {
  83551. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83552. serializationObject.customType = "BABYLON.GridMaterial";
  83553. return serializationObject;
  83554. };
  83555. GridMaterial.prototype.getClassName = function () {
  83556. return "GridMaterial";
  83557. };
  83558. GridMaterial.Parse = function (source, scene, rootUrl) {
  83559. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  83560. };
  83561. __decorate([
  83562. BABYLON.serializeAsColor3()
  83563. ], GridMaterial.prototype, "mainColor", void 0);
  83564. __decorate([
  83565. BABYLON.serializeAsColor3()
  83566. ], GridMaterial.prototype, "lineColor", void 0);
  83567. __decorate([
  83568. BABYLON.serialize()
  83569. ], GridMaterial.prototype, "gridRatio", void 0);
  83570. __decorate([
  83571. BABYLON.serializeAsColor3()
  83572. ], GridMaterial.prototype, "gridOffset", void 0);
  83573. __decorate([
  83574. BABYLON.serialize()
  83575. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  83576. __decorate([
  83577. BABYLON.serialize()
  83578. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  83579. __decorate([
  83580. BABYLON.serialize()
  83581. ], GridMaterial.prototype, "opacity", void 0);
  83582. __decorate([
  83583. BABYLON.serialize()
  83584. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  83585. return GridMaterial;
  83586. }(BABYLON.PushMaterial));
  83587. BABYLON.GridMaterial = GridMaterial;
  83588. })(BABYLON || (BABYLON = {}));
  83589. //# sourceMappingURL=babylon.gridmaterial.js.map
  83590. 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}";
  83591. 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}";
  83592. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  83593. var BABYLON;
  83594. (function (BABYLON) {
  83595. var GLTFLoaderCoordinateSystemMode;
  83596. (function (GLTFLoaderCoordinateSystemMode) {
  83597. /**
  83598. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  83599. */
  83600. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  83601. /**
  83602. * Sets the useRightHandedSystem flag on the scene.
  83603. */
  83604. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  83605. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  83606. var GLTFLoaderAnimationStartMode;
  83607. (function (GLTFLoaderAnimationStartMode) {
  83608. /**
  83609. * No animation will start.
  83610. */
  83611. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  83612. /**
  83613. * The first animation will start.
  83614. */
  83615. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  83616. /**
  83617. * All animations will start.
  83618. */
  83619. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  83620. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  83621. var GLTFFileLoader = /** @class */ (function () {
  83622. function GLTFFileLoader() {
  83623. // #region Common options
  83624. /**
  83625. * Raised when the asset has been parsed.
  83626. * The data.json property stores the glTF JSON.
  83627. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  83628. */
  83629. this.onParsedObservable = new BABYLON.Observable();
  83630. // #endregion
  83631. // #region V2 options
  83632. /**
  83633. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  83634. */
  83635. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  83636. /**
  83637. * The animation start mode (NONE, FIRST, ALL).
  83638. */
  83639. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  83640. /**
  83641. * Set to true to compile materials before raising the success callback.
  83642. */
  83643. this.compileMaterials = false;
  83644. /**
  83645. * Set to true to also compile materials with clip planes.
  83646. */
  83647. this.useClipPlane = false;
  83648. /**
  83649. * Set to true to compile shadow generators before raising the success callback.
  83650. */
  83651. this.compileShadowGenerators = false;
  83652. /**
  83653. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  83654. */
  83655. this.onMeshLoadedObservable = new BABYLON.Observable();
  83656. /**
  83657. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  83658. */
  83659. this.onTextureLoadedObservable = new BABYLON.Observable();
  83660. /**
  83661. * Raised when the loader creates a material after parsing the glTF properties of the material.
  83662. */
  83663. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83664. /**
  83665. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  83666. * For assets with LODs, raised when all of the LODs are complete.
  83667. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  83668. */
  83669. this.onCompleteObservable = new BABYLON.Observable();
  83670. /**
  83671. * Raised when the loader is disposed.
  83672. */
  83673. this.onDisposeObservable = new BABYLON.Observable();
  83674. // #endregion
  83675. this._loader = null;
  83676. this.name = "gltf";
  83677. this.extensions = {
  83678. ".gltf": { isBinary: false },
  83679. ".glb": { isBinary: true }
  83680. };
  83681. }
  83682. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  83683. set: function (callback) {
  83684. if (this._onParsedObserver) {
  83685. this.onParsedObservable.remove(this._onParsedObserver);
  83686. }
  83687. this._onParsedObserver = this.onParsedObservable.add(callback);
  83688. },
  83689. enumerable: true,
  83690. configurable: true
  83691. });
  83692. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  83693. set: function (callback) {
  83694. if (this._onMeshLoadedObserver) {
  83695. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  83696. }
  83697. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  83698. },
  83699. enumerable: true,
  83700. configurable: true
  83701. });
  83702. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  83703. set: function (callback) {
  83704. if (this._onTextureLoadedObserver) {
  83705. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  83706. }
  83707. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  83708. },
  83709. enumerable: true,
  83710. configurable: true
  83711. });
  83712. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  83713. set: function (callback) {
  83714. if (this._onMaterialLoadedObserver) {
  83715. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  83716. }
  83717. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  83718. },
  83719. enumerable: true,
  83720. configurable: true
  83721. });
  83722. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  83723. set: function (callback) {
  83724. if (this._onCompleteObserver) {
  83725. this.onCompleteObservable.remove(this._onCompleteObserver);
  83726. }
  83727. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  83728. },
  83729. enumerable: true,
  83730. configurable: true
  83731. });
  83732. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  83733. set: function (callback) {
  83734. if (this._onDisposeObserver) {
  83735. this.onDisposeObservable.remove(this._onDisposeObserver);
  83736. }
  83737. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  83738. },
  83739. enumerable: true,
  83740. configurable: true
  83741. });
  83742. /**
  83743. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  83744. */
  83745. GLTFFileLoader.prototype.dispose = function () {
  83746. if (this._loader) {
  83747. this._loader.dispose();
  83748. this._loader = null;
  83749. }
  83750. this.onParsedObservable.clear();
  83751. this.onMeshLoadedObservable.clear();
  83752. this.onTextureLoadedObservable.clear();
  83753. this.onMaterialLoadedObservable.clear();
  83754. this.onCompleteObservable.clear();
  83755. this.onDisposeObservable.notifyObservers(this);
  83756. this.onDisposeObservable.clear();
  83757. };
  83758. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  83759. try {
  83760. var loaderData = this._parse(data);
  83761. this._loader = this._getLoader(loaderData);
  83762. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  83763. }
  83764. catch (e) {
  83765. if (onError) {
  83766. onError(e.message, e);
  83767. }
  83768. else {
  83769. BABYLON.Tools.Error(e.message);
  83770. }
  83771. }
  83772. };
  83773. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83774. try {
  83775. var loaderData = this._parse(data);
  83776. this._loader = this._getLoader(loaderData);
  83777. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  83778. }
  83779. catch (e) {
  83780. if (onError) {
  83781. onError(e.message, e);
  83782. }
  83783. else {
  83784. BABYLON.Tools.Error(e.message);
  83785. }
  83786. }
  83787. };
  83788. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83789. try {
  83790. var loaderData = this._parse(data);
  83791. this._loader = this._getLoader(loaderData);
  83792. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  83793. var container = new BABYLON.AssetContainer(scene);
  83794. Array.prototype.push.apply(container.meshes, meshes);
  83795. Array.prototype.push.apply(container.particleSystems, particleSystems);
  83796. Array.prototype.push.apply(container.skeletons, skeletons);
  83797. container.removeAllFromScene();
  83798. onSuccess(container);
  83799. }, onProgress, onError);
  83800. }
  83801. catch (e) {
  83802. if (onError) {
  83803. onError(e.message, e);
  83804. }
  83805. else {
  83806. BABYLON.Tools.Error(e.message);
  83807. }
  83808. }
  83809. };
  83810. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  83811. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  83812. };
  83813. GLTFFileLoader.prototype.createPlugin = function () {
  83814. return new GLTFFileLoader();
  83815. };
  83816. GLTFFileLoader.prototype._parse = function (data) {
  83817. var parsedData;
  83818. if (data instanceof ArrayBuffer) {
  83819. parsedData = GLTFFileLoader._parseBinary(data);
  83820. }
  83821. else {
  83822. parsedData = {
  83823. json: JSON.parse(data),
  83824. bin: null
  83825. };
  83826. }
  83827. this.onParsedObservable.notifyObservers(parsedData);
  83828. return parsedData;
  83829. };
  83830. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  83831. var _this = this;
  83832. var loaderVersion = { major: 2, minor: 0 };
  83833. var asset = loaderData.json.asset || {};
  83834. var version = GLTFFileLoader._parseVersion(asset.version);
  83835. if (!version) {
  83836. throw new Error("Invalid version: " + asset.version);
  83837. }
  83838. if (asset.minVersion !== undefined) {
  83839. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  83840. if (!minVersion) {
  83841. throw new Error("Invalid minimum version: " + asset.minVersion);
  83842. }
  83843. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  83844. throw new Error("Incompatible minimum version: " + asset.minVersion);
  83845. }
  83846. }
  83847. var createLoaders = {
  83848. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  83849. 2: GLTFFileLoader.CreateGLTFLoaderV2
  83850. };
  83851. var createLoader = createLoaders[version.major];
  83852. if (!createLoader) {
  83853. throw new Error("Unsupported version: " + asset.version);
  83854. }
  83855. var loader = createLoader();
  83856. loader.coordinateSystemMode = this.coordinateSystemMode;
  83857. loader.animationStartMode = this.animationStartMode;
  83858. loader.compileMaterials = this.compileMaterials;
  83859. loader.useClipPlane = this.useClipPlane;
  83860. loader.compileShadowGenerators = this.compileShadowGenerators;
  83861. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  83862. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  83863. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  83864. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  83865. return loader;
  83866. };
  83867. GLTFFileLoader._parseBinary = function (data) {
  83868. var Binary = {
  83869. Magic: 0x46546C67
  83870. };
  83871. var binaryReader = new BinaryReader(data);
  83872. var magic = binaryReader.readUint32();
  83873. if (magic !== Binary.Magic) {
  83874. throw new Error("Unexpected magic: " + magic);
  83875. }
  83876. var version = binaryReader.readUint32();
  83877. switch (version) {
  83878. case 1: return GLTFFileLoader._parseV1(binaryReader);
  83879. case 2: return GLTFFileLoader._parseV2(binaryReader);
  83880. }
  83881. throw new Error("Unsupported version: " + version);
  83882. };
  83883. GLTFFileLoader._parseV1 = function (binaryReader) {
  83884. var ContentFormat = {
  83885. JSON: 0
  83886. };
  83887. var length = binaryReader.readUint32();
  83888. if (length != binaryReader.getLength()) {
  83889. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  83890. }
  83891. var contentLength = binaryReader.readUint32();
  83892. var contentFormat = binaryReader.readUint32();
  83893. var content;
  83894. switch (contentFormat) {
  83895. case ContentFormat.JSON: {
  83896. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  83897. break;
  83898. }
  83899. default: {
  83900. throw new Error("Unexpected content format: " + contentFormat);
  83901. }
  83902. }
  83903. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  83904. var body = binaryReader.readUint8Array(bytesRemaining);
  83905. return {
  83906. json: content,
  83907. bin: body
  83908. };
  83909. };
  83910. GLTFFileLoader._parseV2 = function (binaryReader) {
  83911. var ChunkFormat = {
  83912. JSON: 0x4E4F534A,
  83913. BIN: 0x004E4942
  83914. };
  83915. var length = binaryReader.readUint32();
  83916. if (length !== binaryReader.getLength()) {
  83917. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  83918. }
  83919. // JSON chunk
  83920. var chunkLength = binaryReader.readUint32();
  83921. var chunkFormat = binaryReader.readUint32();
  83922. if (chunkFormat !== ChunkFormat.JSON) {
  83923. throw new Error("First chunk format is not JSON");
  83924. }
  83925. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  83926. // Look for BIN chunk
  83927. var bin = null;
  83928. while (binaryReader.getPosition() < binaryReader.getLength()) {
  83929. var chunkLength_1 = binaryReader.readUint32();
  83930. var chunkFormat_1 = binaryReader.readUint32();
  83931. switch (chunkFormat_1) {
  83932. case ChunkFormat.JSON: {
  83933. throw new Error("Unexpected JSON chunk");
  83934. }
  83935. case ChunkFormat.BIN: {
  83936. bin = binaryReader.readUint8Array(chunkLength_1);
  83937. break;
  83938. }
  83939. default: {
  83940. // ignore unrecognized chunkFormat
  83941. binaryReader.skipBytes(chunkLength_1);
  83942. break;
  83943. }
  83944. }
  83945. }
  83946. return {
  83947. json: json,
  83948. bin: bin
  83949. };
  83950. };
  83951. GLTFFileLoader._parseVersion = function (version) {
  83952. if (version === "1.0" || version === "1.0.1") {
  83953. return {
  83954. major: 1,
  83955. minor: 0
  83956. };
  83957. }
  83958. var match = (version + "").match(/^(\d+)\.(\d+)/);
  83959. if (!match) {
  83960. return null;
  83961. }
  83962. return {
  83963. major: parseInt(match[1]),
  83964. minor: parseInt(match[2])
  83965. };
  83966. };
  83967. GLTFFileLoader._compareVersion = function (a, b) {
  83968. if (a.major > b.major)
  83969. return 1;
  83970. if (a.major < b.major)
  83971. return -1;
  83972. if (a.minor > b.minor)
  83973. return 1;
  83974. if (a.minor < b.minor)
  83975. return -1;
  83976. return 0;
  83977. };
  83978. GLTFFileLoader._decodeBufferToText = function (buffer) {
  83979. var result = "";
  83980. var length = buffer.byteLength;
  83981. for (var i = 0; i < length; i++) {
  83982. result += String.fromCharCode(buffer[i]);
  83983. }
  83984. return result;
  83985. };
  83986. // #endregion
  83987. // #region V1 options
  83988. GLTFFileLoader.IncrementalLoading = true;
  83989. GLTFFileLoader.HomogeneousCoordinates = false;
  83990. return GLTFFileLoader;
  83991. }());
  83992. BABYLON.GLTFFileLoader = GLTFFileLoader;
  83993. var BinaryReader = /** @class */ (function () {
  83994. function BinaryReader(arrayBuffer) {
  83995. this._arrayBuffer = arrayBuffer;
  83996. this._dataView = new DataView(arrayBuffer);
  83997. this._byteOffset = 0;
  83998. }
  83999. BinaryReader.prototype.getPosition = function () {
  84000. return this._byteOffset;
  84001. };
  84002. BinaryReader.prototype.getLength = function () {
  84003. return this._arrayBuffer.byteLength;
  84004. };
  84005. BinaryReader.prototype.readUint32 = function () {
  84006. var value = this._dataView.getUint32(this._byteOffset, true);
  84007. this._byteOffset += 4;
  84008. return value;
  84009. };
  84010. BinaryReader.prototype.readUint8Array = function (length) {
  84011. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  84012. this._byteOffset += length;
  84013. return value;
  84014. };
  84015. BinaryReader.prototype.skipBytes = function (length) {
  84016. this._byteOffset += length;
  84017. };
  84018. return BinaryReader;
  84019. }());
  84020. if (BABYLON.SceneLoader) {
  84021. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  84022. }
  84023. })(BABYLON || (BABYLON = {}));
  84024. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  84025. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84026. var BABYLON;
  84027. (function (BABYLON) {
  84028. var GLTF1;
  84029. (function (GLTF1) {
  84030. /**
  84031. * Enums
  84032. */
  84033. var EComponentType;
  84034. (function (EComponentType) {
  84035. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84036. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84037. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84038. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84039. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84040. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  84041. var EShaderType;
  84042. (function (EShaderType) {
  84043. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  84044. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  84045. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  84046. var EParameterType;
  84047. (function (EParameterType) {
  84048. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  84049. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84050. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  84051. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84052. EParameterType[EParameterType["INT"] = 5124] = "INT";
  84053. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84054. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  84055. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  84056. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  84057. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  84058. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  84059. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  84060. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  84061. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  84062. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  84063. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  84064. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  84065. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  84066. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  84067. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  84068. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  84069. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  84070. var ETextureWrapMode;
  84071. (function (ETextureWrapMode) {
  84072. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84073. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84074. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84075. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  84076. var ETextureFilterType;
  84077. (function (ETextureFilterType) {
  84078. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  84079. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  84080. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84081. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84082. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84083. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84084. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  84085. var ETextureFormat;
  84086. (function (ETextureFormat) {
  84087. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  84088. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  84089. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  84090. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  84091. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  84092. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  84093. var ECullingType;
  84094. (function (ECullingType) {
  84095. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  84096. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  84097. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  84098. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  84099. var EBlendingFunction;
  84100. (function (EBlendingFunction) {
  84101. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  84102. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  84103. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  84104. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  84105. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  84106. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  84107. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  84108. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  84109. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  84110. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  84111. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  84112. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  84113. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  84114. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  84115. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  84116. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  84117. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84118. })(BABYLON || (BABYLON = {}));
  84119. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84120. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84121. var BABYLON;
  84122. (function (BABYLON) {
  84123. var GLTF1;
  84124. (function (GLTF1) {
  84125. /**
  84126. * Tokenizer. Used for shaders compatibility
  84127. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  84128. */
  84129. var ETokenType;
  84130. (function (ETokenType) {
  84131. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  84132. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  84133. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  84134. })(ETokenType || (ETokenType = {}));
  84135. var Tokenizer = /** @class */ (function () {
  84136. function Tokenizer(toParse) {
  84137. this._pos = 0;
  84138. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  84139. this._toParse = toParse;
  84140. this._maxPos = toParse.length;
  84141. }
  84142. Tokenizer.prototype.getNextToken = function () {
  84143. if (this.isEnd())
  84144. return ETokenType.END_OF_INPUT;
  84145. this.currentString = this.read();
  84146. this.currentToken = ETokenType.UNKNOWN;
  84147. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  84148. this.currentToken = ETokenType.IDENTIFIER;
  84149. this.currentIdentifier = this.currentString;
  84150. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  84151. this.currentIdentifier += this.currentString;
  84152. this.forward();
  84153. }
  84154. }
  84155. return this.currentToken;
  84156. };
  84157. Tokenizer.prototype.peek = function () {
  84158. return this._toParse[this._pos];
  84159. };
  84160. Tokenizer.prototype.read = function () {
  84161. return this._toParse[this._pos++];
  84162. };
  84163. Tokenizer.prototype.forward = function () {
  84164. this._pos++;
  84165. };
  84166. Tokenizer.prototype.isEnd = function () {
  84167. return this._pos >= this._maxPos;
  84168. };
  84169. return Tokenizer;
  84170. }());
  84171. /**
  84172. * Values
  84173. */
  84174. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  84175. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  84176. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  84177. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  84178. /**
  84179. * Parse
  84180. */
  84181. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  84182. for (var buf in parsedBuffers) {
  84183. var parsedBuffer = parsedBuffers[buf];
  84184. gltfRuntime.buffers[buf] = parsedBuffer;
  84185. gltfRuntime.buffersCount++;
  84186. }
  84187. };
  84188. var parseShaders = function (parsedShaders, gltfRuntime) {
  84189. for (var sha in parsedShaders) {
  84190. var parsedShader = parsedShaders[sha];
  84191. gltfRuntime.shaders[sha] = parsedShader;
  84192. gltfRuntime.shaderscount++;
  84193. }
  84194. };
  84195. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  84196. for (var object in parsedObjects) {
  84197. var parsedObject = parsedObjects[object];
  84198. gltfRuntime[runtimeProperty][object] = parsedObject;
  84199. }
  84200. };
  84201. /**
  84202. * Utils
  84203. */
  84204. var normalizeUVs = function (buffer) {
  84205. if (!buffer) {
  84206. return;
  84207. }
  84208. for (var i = 0; i < buffer.length / 2; i++) {
  84209. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  84210. }
  84211. };
  84212. var getAttribute = function (attributeParameter) {
  84213. if (attributeParameter.semantic === "NORMAL") {
  84214. return "normal";
  84215. }
  84216. else if (attributeParameter.semantic === "POSITION") {
  84217. return "position";
  84218. }
  84219. else if (attributeParameter.semantic === "JOINT") {
  84220. return "matricesIndices";
  84221. }
  84222. else if (attributeParameter.semantic === "WEIGHT") {
  84223. return "matricesWeights";
  84224. }
  84225. else if (attributeParameter.semantic === "COLOR") {
  84226. return "color";
  84227. }
  84228. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  84229. var channel = Number(attributeParameter.semantic.split("_")[1]);
  84230. return "uv" + (channel === 0 ? "" : channel + 1);
  84231. }
  84232. return null;
  84233. };
  84234. /**
  84235. * Loads and creates animations
  84236. */
  84237. var loadAnimations = function (gltfRuntime) {
  84238. for (var anim in gltfRuntime.animations) {
  84239. var animation = gltfRuntime.animations[anim];
  84240. if (!animation.channels || !animation.samplers) {
  84241. continue;
  84242. }
  84243. var lastAnimation = null;
  84244. for (var i = 0; i < animation.channels.length; i++) {
  84245. // Get parameters and load buffers
  84246. var channel = animation.channels[i];
  84247. var sampler = animation.samplers[channel.sampler];
  84248. if (!sampler) {
  84249. continue;
  84250. }
  84251. var inputData = null;
  84252. var outputData = null;
  84253. if (animation.parameters) {
  84254. inputData = animation.parameters[sampler.input];
  84255. outputData = animation.parameters[sampler.output];
  84256. }
  84257. else {
  84258. inputData = sampler.input;
  84259. outputData = sampler.output;
  84260. }
  84261. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  84262. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  84263. var targetID = channel.target.id;
  84264. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  84265. if (targetNode === null) {
  84266. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  84267. }
  84268. if (targetNode === null) {
  84269. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  84270. continue;
  84271. }
  84272. var isBone = targetNode instanceof BABYLON.Bone;
  84273. // Get target path (position, rotation or scaling)
  84274. var targetPath = channel.target.path;
  84275. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  84276. if (targetPathIndex !== -1) {
  84277. targetPath = babylonAnimationPaths[targetPathIndex];
  84278. }
  84279. // Determine animation type
  84280. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  84281. if (!isBone) {
  84282. if (targetPath === "rotationQuaternion") {
  84283. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  84284. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  84285. }
  84286. else {
  84287. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  84288. }
  84289. }
  84290. // Create animation and key frames
  84291. var babylonAnimation = null;
  84292. var keys = [];
  84293. var arrayOffset = 0;
  84294. var modifyKey = false;
  84295. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  84296. babylonAnimation = lastAnimation;
  84297. modifyKey = true;
  84298. }
  84299. if (!modifyKey) {
  84300. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  84301. }
  84302. // For each frame
  84303. for (var j = 0; j < bufferInput.length; j++) {
  84304. var value = null;
  84305. if (targetPath === "rotationQuaternion") {
  84306. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  84307. arrayOffset += 4;
  84308. }
  84309. else {
  84310. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  84311. arrayOffset += 3;
  84312. }
  84313. if (isBone) {
  84314. var bone = targetNode;
  84315. var translation = BABYLON.Vector3.Zero();
  84316. var rotationQuaternion = new BABYLON.Quaternion();
  84317. var scaling = BABYLON.Vector3.Zero();
  84318. // Warning on decompose
  84319. var mat = bone.getBaseMatrix();
  84320. if (modifyKey && lastAnimation) {
  84321. mat = lastAnimation.getKeys()[j].value;
  84322. }
  84323. mat.decompose(scaling, rotationQuaternion, translation);
  84324. if (targetPath === "position") {
  84325. translation = value;
  84326. }
  84327. else if (targetPath === "rotationQuaternion") {
  84328. rotationQuaternion = value;
  84329. }
  84330. else {
  84331. scaling = value;
  84332. }
  84333. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  84334. }
  84335. if (!modifyKey) {
  84336. keys.push({
  84337. frame: bufferInput[j],
  84338. value: value
  84339. });
  84340. }
  84341. else if (lastAnimation) {
  84342. lastAnimation.getKeys()[j].value = value;
  84343. }
  84344. }
  84345. // Finish
  84346. if (!modifyKey && babylonAnimation) {
  84347. babylonAnimation.setKeys(keys);
  84348. targetNode.animations.push(babylonAnimation);
  84349. }
  84350. lastAnimation = babylonAnimation;
  84351. gltfRuntime.scene.stopAnimation(targetNode);
  84352. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  84353. }
  84354. }
  84355. };
  84356. /**
  84357. * Returns the bones transformation matrix
  84358. */
  84359. var configureBoneTransformation = function (node) {
  84360. var mat = null;
  84361. if (node.translation || node.rotation || node.scale) {
  84362. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  84363. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  84364. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  84365. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  84366. }
  84367. else {
  84368. mat = BABYLON.Matrix.FromArray(node.matrix);
  84369. }
  84370. return mat;
  84371. };
  84372. /**
  84373. * Returns the parent bone
  84374. */
  84375. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  84376. // Try to find
  84377. for (var i = 0; i < newSkeleton.bones.length; i++) {
  84378. if (newSkeleton.bones[i].name === jointName) {
  84379. return newSkeleton.bones[i];
  84380. }
  84381. }
  84382. // Not found, search in gltf nodes
  84383. var nodes = gltfRuntime.nodes;
  84384. for (var nde in nodes) {
  84385. var node = nodes[nde];
  84386. if (!node.jointName) {
  84387. continue;
  84388. }
  84389. var children = node.children;
  84390. for (var i = 0; i < children.length; i++) {
  84391. var child = gltfRuntime.nodes[children[i]];
  84392. if (!child.jointName) {
  84393. continue;
  84394. }
  84395. if (child.jointName === jointName) {
  84396. var mat = configureBoneTransformation(node);
  84397. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  84398. bone.id = nde;
  84399. return bone;
  84400. }
  84401. }
  84402. }
  84403. return null;
  84404. };
  84405. /**
  84406. * Returns the appropriate root node
  84407. */
  84408. var getNodeToRoot = function (nodesToRoot, id) {
  84409. for (var i = 0; i < nodesToRoot.length; i++) {
  84410. var nodeToRoot = nodesToRoot[i];
  84411. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  84412. var child = nodeToRoot.node.children[j];
  84413. if (child === id) {
  84414. return nodeToRoot.bone;
  84415. }
  84416. }
  84417. }
  84418. return null;
  84419. };
  84420. /**
  84421. * Returns the node with the joint name
  84422. */
  84423. var getJointNode = function (gltfRuntime, jointName) {
  84424. var nodes = gltfRuntime.nodes;
  84425. var node = nodes[jointName];
  84426. if (node) {
  84427. return {
  84428. node: node,
  84429. id: jointName
  84430. };
  84431. }
  84432. for (var nde in nodes) {
  84433. node = nodes[nde];
  84434. if (node.jointName === jointName) {
  84435. return {
  84436. node: node,
  84437. id: nde
  84438. };
  84439. }
  84440. }
  84441. return null;
  84442. };
  84443. /**
  84444. * Checks if a nodes is in joints
  84445. */
  84446. var nodeIsInJoints = function (skins, id) {
  84447. for (var i = 0; i < skins.jointNames.length; i++) {
  84448. if (skins.jointNames[i] === id) {
  84449. return true;
  84450. }
  84451. }
  84452. return false;
  84453. };
  84454. /**
  84455. * Fills the nodes to root for bones and builds hierarchy
  84456. */
  84457. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  84458. // Creates nodes for root
  84459. for (var nde in gltfRuntime.nodes) {
  84460. var node = gltfRuntime.nodes[nde];
  84461. var id = nde;
  84462. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  84463. continue;
  84464. }
  84465. // Create node to root bone
  84466. var mat = configureBoneTransformation(node);
  84467. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  84468. bone.id = id;
  84469. nodesToRoot.push({ bone: bone, node: node, id: id });
  84470. }
  84471. // Parenting
  84472. for (var i = 0; i < nodesToRoot.length; i++) {
  84473. var nodeToRoot = nodesToRoot[i];
  84474. var children = nodeToRoot.node.children;
  84475. for (var j = 0; j < children.length; j++) {
  84476. var child = null;
  84477. for (var k = 0; k < nodesToRoot.length; k++) {
  84478. if (nodesToRoot[k].id === children[j]) {
  84479. child = nodesToRoot[k];
  84480. break;
  84481. }
  84482. }
  84483. if (child) {
  84484. child.bone._parent = nodeToRoot.bone;
  84485. nodeToRoot.bone.children.push(child.bone);
  84486. }
  84487. }
  84488. }
  84489. };
  84490. /**
  84491. * Imports a skeleton
  84492. */
  84493. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  84494. if (!newSkeleton) {
  84495. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  84496. }
  84497. if (!skins.babylonSkeleton) {
  84498. return newSkeleton;
  84499. }
  84500. // Find the root bones
  84501. var nodesToRoot = [];
  84502. var nodesToRootToAdd = [];
  84503. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  84504. newSkeleton.bones = [];
  84505. // Joints
  84506. for (var i = 0; i < skins.jointNames.length; i++) {
  84507. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  84508. if (!jointNode) {
  84509. continue;
  84510. }
  84511. var node = jointNode.node;
  84512. if (!node) {
  84513. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  84514. continue;
  84515. }
  84516. var id = jointNode.id;
  84517. // Optimize, if the bone already exists...
  84518. var existingBone = gltfRuntime.scene.getBoneByID(id);
  84519. if (existingBone) {
  84520. newSkeleton.bones.push(existingBone);
  84521. continue;
  84522. }
  84523. // Search for parent bone
  84524. var foundBone = false;
  84525. var parentBone = null;
  84526. for (var j = 0; j < i; j++) {
  84527. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  84528. if (!jointNode_1) {
  84529. continue;
  84530. }
  84531. var joint = jointNode_1.node;
  84532. if (!joint) {
  84533. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  84534. continue;
  84535. }
  84536. var children = joint.children;
  84537. if (!children) {
  84538. continue;
  84539. }
  84540. foundBone = false;
  84541. for (var k = 0; k < children.length; k++) {
  84542. if (children[k] === id) {
  84543. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  84544. foundBone = true;
  84545. break;
  84546. }
  84547. }
  84548. if (foundBone) {
  84549. break;
  84550. }
  84551. }
  84552. // Create bone
  84553. var mat = configureBoneTransformation(node);
  84554. if (!parentBone && nodesToRoot.length > 0) {
  84555. parentBone = getNodeToRoot(nodesToRoot, id);
  84556. if (parentBone) {
  84557. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  84558. nodesToRootToAdd.push(parentBone);
  84559. }
  84560. }
  84561. }
  84562. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  84563. bone.id = id;
  84564. }
  84565. // Polish
  84566. var bones = newSkeleton.bones;
  84567. newSkeleton.bones = [];
  84568. for (var i = 0; i < skins.jointNames.length; i++) {
  84569. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  84570. if (!jointNode) {
  84571. continue;
  84572. }
  84573. for (var j = 0; j < bones.length; j++) {
  84574. if (bones[j].id === jointNode.id) {
  84575. newSkeleton.bones.push(bones[j]);
  84576. break;
  84577. }
  84578. }
  84579. }
  84580. newSkeleton.prepare();
  84581. // Finish
  84582. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  84583. newSkeleton.bones.push(nodesToRootToAdd[i]);
  84584. }
  84585. return newSkeleton;
  84586. };
  84587. /**
  84588. * Imports a mesh and its geometries
  84589. */
  84590. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  84591. if (!newMesh) {
  84592. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  84593. newMesh.id = id;
  84594. }
  84595. if (!node.babylonNode) {
  84596. return newMesh;
  84597. }
  84598. var subMaterials = [];
  84599. var vertexData = new BABYLON.VertexData();
  84600. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  84601. var verticesStarts = new Array();
  84602. var verticesCounts = new Array();
  84603. var indexStarts = new Array();
  84604. var indexCounts = new Array();
  84605. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  84606. var meshID = meshes[meshIndex];
  84607. var mesh = gltfRuntime.meshes[meshID];
  84608. if (!mesh) {
  84609. continue;
  84610. }
  84611. // Positions, normals and UVs
  84612. for (var i = 0; i < mesh.primitives.length; i++) {
  84613. // Temporary vertex data
  84614. var tempVertexData = new BABYLON.VertexData();
  84615. var primitive = mesh.primitives[i];
  84616. if (primitive.mode !== 4) {
  84617. // continue;
  84618. }
  84619. var attributes = primitive.attributes;
  84620. var accessor = null;
  84621. var buffer = null;
  84622. // Set positions, normal and uvs
  84623. for (var semantic in attributes) {
  84624. // Link accessor and buffer view
  84625. accessor = gltfRuntime.accessors[attributes[semantic]];
  84626. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  84627. if (semantic === "NORMAL") {
  84628. tempVertexData.normals = new Float32Array(buffer.length);
  84629. tempVertexData.normals.set(buffer);
  84630. }
  84631. else if (semantic === "POSITION") {
  84632. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  84633. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  84634. for (var j = 0; j < buffer.length; j += 4) {
  84635. tempVertexData.positions[j] = buffer[j];
  84636. tempVertexData.positions[j + 1] = buffer[j + 1];
  84637. tempVertexData.positions[j + 2] = buffer[j + 2];
  84638. }
  84639. }
  84640. else {
  84641. tempVertexData.positions = new Float32Array(buffer.length);
  84642. tempVertexData.positions.set(buffer);
  84643. }
  84644. verticesCounts.push(tempVertexData.positions.length);
  84645. }
  84646. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  84647. var channel = Number(semantic.split("_")[1]);
  84648. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  84649. var uvs = new Float32Array(buffer.length);
  84650. uvs.set(buffer);
  84651. normalizeUVs(uvs);
  84652. tempVertexData.set(uvs, uvKind);
  84653. }
  84654. else if (semantic === "JOINT") {
  84655. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  84656. tempVertexData.matricesIndices.set(buffer);
  84657. }
  84658. else if (semantic === "WEIGHT") {
  84659. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  84660. tempVertexData.matricesWeights.set(buffer);
  84661. }
  84662. else if (semantic === "COLOR") {
  84663. tempVertexData.colors = new Float32Array(buffer.length);
  84664. tempVertexData.colors.set(buffer);
  84665. }
  84666. }
  84667. // Indices
  84668. accessor = gltfRuntime.accessors[primitive.indices];
  84669. if (accessor) {
  84670. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  84671. tempVertexData.indices = new Int32Array(buffer.length);
  84672. tempVertexData.indices.set(buffer);
  84673. indexCounts.push(tempVertexData.indices.length);
  84674. }
  84675. else {
  84676. // Set indices on the fly
  84677. var indices = [];
  84678. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  84679. indices.push(j);
  84680. }
  84681. tempVertexData.indices = new Int32Array(indices);
  84682. indexCounts.push(tempVertexData.indices.length);
  84683. }
  84684. vertexData.merge(tempVertexData);
  84685. // Sub material
  84686. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  84687. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  84688. // Update vertices start and index start
  84689. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  84690. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  84691. }
  84692. }
  84693. var material;
  84694. if (subMaterials.length > 1) {
  84695. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  84696. material.subMaterials = subMaterials;
  84697. }
  84698. else {
  84699. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  84700. }
  84701. if (subMaterials.length === 1) {
  84702. material = subMaterials[0];
  84703. }
  84704. if (!newMesh.material) {
  84705. newMesh.material = material;
  84706. }
  84707. // Apply geometry
  84708. geometry.setAllVerticesData(vertexData, false);
  84709. newMesh.computeWorldMatrix(true);
  84710. // Apply submeshes
  84711. newMesh.subMeshes = [];
  84712. var index = 0;
  84713. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  84714. var meshID = meshes[meshIndex];
  84715. var mesh = gltfRuntime.meshes[meshID];
  84716. if (!mesh) {
  84717. continue;
  84718. }
  84719. for (var i = 0; i < mesh.primitives.length; i++) {
  84720. if (mesh.primitives[i].mode !== 4) {
  84721. //continue;
  84722. }
  84723. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  84724. index++;
  84725. }
  84726. }
  84727. // Finish
  84728. return newMesh;
  84729. };
  84730. /**
  84731. * Configure node transformation from position, rotation and scaling
  84732. */
  84733. var configureNode = function (newNode, position, rotation, scaling) {
  84734. if (newNode.position) {
  84735. newNode.position = position;
  84736. }
  84737. if (newNode.rotationQuaternion || newNode.rotation) {
  84738. newNode.rotationQuaternion = rotation;
  84739. }
  84740. if (newNode.scaling) {
  84741. newNode.scaling = scaling;
  84742. }
  84743. };
  84744. /**
  84745. * Configures node from transformation matrix
  84746. */
  84747. var configureNodeFromMatrix = function (newNode, node, parent) {
  84748. if (node.matrix) {
  84749. var position = new BABYLON.Vector3(0, 0, 0);
  84750. var rotation = new BABYLON.Quaternion();
  84751. var scaling = new BABYLON.Vector3(0, 0, 0);
  84752. var mat = BABYLON.Matrix.FromArray(node.matrix);
  84753. mat.decompose(scaling, rotation, position);
  84754. configureNode(newNode, position, rotation, scaling);
  84755. }
  84756. else if (node.translation && node.rotation && node.scale) {
  84757. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  84758. }
  84759. newNode.computeWorldMatrix(true);
  84760. };
  84761. /**
  84762. * Imports a node
  84763. */
  84764. var importNode = function (gltfRuntime, node, id, parent) {
  84765. var lastNode = null;
  84766. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  84767. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  84768. return null;
  84769. }
  84770. }
  84771. // Meshes
  84772. if (node.skin) {
  84773. if (node.meshes) {
  84774. var skin = gltfRuntime.skins[node.skin];
  84775. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  84776. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  84777. if (newMesh.skeleton === null) {
  84778. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  84779. if (!skin.babylonSkeleton) {
  84780. skin.babylonSkeleton = newMesh.skeleton;
  84781. }
  84782. }
  84783. lastNode = newMesh;
  84784. }
  84785. }
  84786. else if (node.meshes) {
  84787. /**
  84788. * Improve meshes property
  84789. */
  84790. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  84791. lastNode = newMesh;
  84792. }
  84793. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  84794. var light = gltfRuntime.lights[node.light];
  84795. if (light) {
  84796. if (light.type === "ambient") {
  84797. var ambienLight = light[light.type];
  84798. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  84799. hemiLight.name = node.name || "";
  84800. if (ambienLight.color) {
  84801. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  84802. }
  84803. lastNode = hemiLight;
  84804. }
  84805. else if (light.type === "directional") {
  84806. var directionalLight = light[light.type];
  84807. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  84808. dirLight.name = node.name || "";
  84809. if (directionalLight.color) {
  84810. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  84811. }
  84812. lastNode = dirLight;
  84813. }
  84814. else if (light.type === "point") {
  84815. var pointLight = light[light.type];
  84816. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  84817. ptLight.name = node.name || "";
  84818. if (pointLight.color) {
  84819. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  84820. }
  84821. lastNode = ptLight;
  84822. }
  84823. else if (light.type === "spot") {
  84824. var spotLight = light[light.type];
  84825. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  84826. spLight.name = node.name || "";
  84827. if (spotLight.color) {
  84828. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  84829. }
  84830. if (spotLight.fallOfAngle) {
  84831. spLight.angle = spotLight.fallOfAngle;
  84832. }
  84833. if (spotLight.fallOffExponent) {
  84834. spLight.exponent = spotLight.fallOffExponent;
  84835. }
  84836. lastNode = spLight;
  84837. }
  84838. }
  84839. }
  84840. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  84841. var camera = gltfRuntime.cameras[node.camera];
  84842. if (camera) {
  84843. if (camera.type === "orthographic") {
  84844. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  84845. orthoCamera.name = node.name || "";
  84846. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  84847. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  84848. lastNode = orthoCamera;
  84849. }
  84850. else if (camera.type === "perspective") {
  84851. var perspectiveCamera = camera[camera.type];
  84852. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  84853. persCamera.name = node.name || "";
  84854. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  84855. if (!perspectiveCamera.aspectRatio) {
  84856. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  84857. }
  84858. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  84859. persCamera.maxZ = perspectiveCamera.zfar;
  84860. persCamera.minZ = perspectiveCamera.znear;
  84861. }
  84862. lastNode = persCamera;
  84863. }
  84864. }
  84865. }
  84866. // Empty node
  84867. if (!node.jointName) {
  84868. if (node.babylonNode) {
  84869. return node.babylonNode;
  84870. }
  84871. else if (lastNode === null) {
  84872. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  84873. node.babylonNode = dummy;
  84874. lastNode = dummy;
  84875. }
  84876. }
  84877. if (lastNode !== null) {
  84878. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  84879. configureNodeFromMatrix(lastNode, node, parent);
  84880. }
  84881. else {
  84882. var translation = node.translation || [0, 0, 0];
  84883. var rotation = node.rotation || [0, 0, 0, 1];
  84884. var scale = node.scale || [1, 1, 1];
  84885. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  84886. }
  84887. lastNode.updateCache(true);
  84888. node.babylonNode = lastNode;
  84889. }
  84890. return lastNode;
  84891. };
  84892. /**
  84893. * Traverses nodes and creates them
  84894. */
  84895. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  84896. if (meshIncluded === void 0) { meshIncluded = false; }
  84897. var node = gltfRuntime.nodes[id];
  84898. var newNode = null;
  84899. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  84900. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  84901. meshIncluded = true;
  84902. }
  84903. else {
  84904. meshIncluded = false;
  84905. }
  84906. }
  84907. else {
  84908. meshIncluded = true;
  84909. }
  84910. if (!node.jointName && meshIncluded) {
  84911. newNode = importNode(gltfRuntime, node, id, parent);
  84912. if (newNode !== null) {
  84913. newNode.id = id;
  84914. newNode.parent = parent;
  84915. }
  84916. }
  84917. if (node.children) {
  84918. for (var i = 0; i < node.children.length; i++) {
  84919. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  84920. }
  84921. }
  84922. };
  84923. /**
  84924. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  84925. */
  84926. var postLoad = function (gltfRuntime) {
  84927. // Nodes
  84928. var currentScene = gltfRuntime.currentScene;
  84929. if (currentScene) {
  84930. for (var i = 0; i < currentScene.nodes.length; i++) {
  84931. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  84932. }
  84933. }
  84934. else {
  84935. for (var thing in gltfRuntime.scenes) {
  84936. currentScene = gltfRuntime.scenes[thing];
  84937. for (var i = 0; i < currentScene.nodes.length; i++) {
  84938. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  84939. }
  84940. }
  84941. }
  84942. // Set animations
  84943. loadAnimations(gltfRuntime);
  84944. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  84945. var skeleton = gltfRuntime.scene.skeletons[i];
  84946. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  84947. }
  84948. };
  84949. /**
  84950. * onBind shaderrs callback to set uniforms and matrices
  84951. */
  84952. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  84953. var materialValues = material.values || technique.parameters;
  84954. for (var unif in unTreatedUniforms) {
  84955. var uniform = unTreatedUniforms[unif];
  84956. var type = uniform.type;
  84957. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  84958. if (uniform.semantic && !uniform.source && !uniform.node) {
  84959. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  84960. }
  84961. else if (uniform.semantic && (uniform.source || uniform.node)) {
  84962. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  84963. if (source === null) {
  84964. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  84965. }
  84966. if (source === null) {
  84967. continue;
  84968. }
  84969. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  84970. }
  84971. }
  84972. else {
  84973. var value = materialValues[technique.uniforms[unif]];
  84974. if (!value) {
  84975. continue;
  84976. }
  84977. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  84978. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  84979. if (texture === null || texture === undefined) {
  84980. continue;
  84981. }
  84982. shaderMaterial.getEffect().setTexture(unif, texture);
  84983. }
  84984. else {
  84985. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  84986. }
  84987. }
  84988. }
  84989. onSuccess(shaderMaterial);
  84990. };
  84991. /**
  84992. * Prepare uniforms to send the only one time
  84993. * Loads the appropriate textures
  84994. */
  84995. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  84996. var materialValues = material.values || technique.parameters;
  84997. var techniqueUniforms = technique.uniforms;
  84998. /**
  84999. * Prepare values here (not matrices)
  85000. */
  85001. for (var unif in unTreatedUniforms) {
  85002. var uniform = unTreatedUniforms[unif];
  85003. var type = uniform.type;
  85004. var value = materialValues[techniqueUniforms[unif]];
  85005. if (value === undefined) {
  85006. // In case the value is the same for all materials
  85007. value = uniform.value;
  85008. }
  85009. if (!value) {
  85010. continue;
  85011. }
  85012. var onLoadTexture = function (uniformName) {
  85013. return function (texture) {
  85014. if (uniform.value && uniformName) {
  85015. // Static uniform
  85016. shaderMaterial.setTexture(uniformName, texture);
  85017. delete unTreatedUniforms[uniformName];
  85018. }
  85019. };
  85020. };
  85021. // Texture (sampler2D)
  85022. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  85023. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  85024. }
  85025. else {
  85026. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  85027. // Static uniform
  85028. delete unTreatedUniforms[unif];
  85029. }
  85030. }
  85031. }
  85032. };
  85033. /**
  85034. * Shader compilation failed
  85035. */
  85036. var onShaderCompileError = function (program, shaderMaterial, onError) {
  85037. return function (effect, error) {
  85038. shaderMaterial.dispose(true);
  85039. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  85040. };
  85041. };
  85042. /**
  85043. * Shader compilation success
  85044. */
  85045. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  85046. return function (_) {
  85047. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  85048. shaderMaterial.onBind = function (mesh) {
  85049. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  85050. };
  85051. };
  85052. };
  85053. /**
  85054. * Returns the appropriate uniform if already handled by babylon
  85055. */
  85056. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  85057. for (var unif in technique.uniforms) {
  85058. var uniform = technique.uniforms[unif];
  85059. var uniformParameter = technique.parameters[uniform];
  85060. if (tokenizer.currentIdentifier === unif) {
  85061. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  85062. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  85063. if (transformIndex !== -1) {
  85064. delete unTreatedUniforms[unif];
  85065. return babylonTransforms[transformIndex];
  85066. }
  85067. }
  85068. }
  85069. }
  85070. return tokenizer.currentIdentifier;
  85071. };
  85072. /**
  85073. * All shaders loaded. Create materials one by one
  85074. */
  85075. var importMaterials = function (gltfRuntime) {
  85076. // Create materials
  85077. for (var mat in gltfRuntime.materials) {
  85078. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  85079. }
  85080. };
  85081. /**
  85082. * Implementation of the base glTF spec
  85083. */
  85084. var GLTFLoaderBase = /** @class */ (function () {
  85085. function GLTFLoaderBase() {
  85086. }
  85087. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  85088. var gltfRuntime = {
  85089. extensions: {},
  85090. accessors: {},
  85091. buffers: {},
  85092. bufferViews: {},
  85093. meshes: {},
  85094. lights: {},
  85095. cameras: {},
  85096. nodes: {},
  85097. images: {},
  85098. textures: {},
  85099. shaders: {},
  85100. programs: {},
  85101. samplers: {},
  85102. techniques: {},
  85103. materials: {},
  85104. animations: {},
  85105. skins: {},
  85106. extensionsUsed: [],
  85107. scenes: {},
  85108. buffersCount: 0,
  85109. shaderscount: 0,
  85110. scene: scene,
  85111. rootUrl: rootUrl,
  85112. loadedBufferCount: 0,
  85113. loadedBufferViews: {},
  85114. loadedShaderCount: 0,
  85115. importOnlyMeshes: false,
  85116. dummyNodes: []
  85117. };
  85118. // Parse
  85119. if (parsedData.extensions) {
  85120. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  85121. }
  85122. if (parsedData.extensionsUsed) {
  85123. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  85124. }
  85125. if (parsedData.buffers) {
  85126. parseBuffers(parsedData.buffers, gltfRuntime);
  85127. }
  85128. if (parsedData.bufferViews) {
  85129. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  85130. }
  85131. if (parsedData.accessors) {
  85132. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  85133. }
  85134. if (parsedData.meshes) {
  85135. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  85136. }
  85137. if (parsedData.lights) {
  85138. parseObject(parsedData.lights, "lights", gltfRuntime);
  85139. }
  85140. if (parsedData.cameras) {
  85141. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  85142. }
  85143. if (parsedData.nodes) {
  85144. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  85145. }
  85146. if (parsedData.images) {
  85147. parseObject(parsedData.images, "images", gltfRuntime);
  85148. }
  85149. if (parsedData.textures) {
  85150. parseObject(parsedData.textures, "textures", gltfRuntime);
  85151. }
  85152. if (parsedData.shaders) {
  85153. parseShaders(parsedData.shaders, gltfRuntime);
  85154. }
  85155. if (parsedData.programs) {
  85156. parseObject(parsedData.programs, "programs", gltfRuntime);
  85157. }
  85158. if (parsedData.samplers) {
  85159. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  85160. }
  85161. if (parsedData.techniques) {
  85162. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  85163. }
  85164. if (parsedData.materials) {
  85165. parseObject(parsedData.materials, "materials", gltfRuntime);
  85166. }
  85167. if (parsedData.animations) {
  85168. parseObject(parsedData.animations, "animations", gltfRuntime);
  85169. }
  85170. if (parsedData.skins) {
  85171. parseObject(parsedData.skins, "skins", gltfRuntime);
  85172. }
  85173. if (parsedData.scenes) {
  85174. gltfRuntime.scenes = parsedData.scenes;
  85175. }
  85176. if (parsedData.scene && parsedData.scenes) {
  85177. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  85178. }
  85179. return gltfRuntime;
  85180. };
  85181. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  85182. var buffer = gltfRuntime.buffers[id];
  85183. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  85184. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  85185. }
  85186. else {
  85187. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  85188. if (request) {
  85189. onError(request.status + " " + request.statusText);
  85190. }
  85191. });
  85192. }
  85193. };
  85194. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  85195. var texture = gltfRuntime.textures[id];
  85196. if (!texture || !texture.source) {
  85197. onError("");
  85198. return;
  85199. }
  85200. if (texture.babylonTexture) {
  85201. onSuccess(null);
  85202. return;
  85203. }
  85204. var source = gltfRuntime.images[texture.source];
  85205. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  85206. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  85207. }
  85208. else {
  85209. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  85210. if (request) {
  85211. onError(request.status + " " + request.statusText);
  85212. }
  85213. });
  85214. }
  85215. };
  85216. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  85217. var texture = gltfRuntime.textures[id];
  85218. if (texture.babylonTexture) {
  85219. onSuccess(texture.babylonTexture);
  85220. return;
  85221. }
  85222. var sampler = gltfRuntime.samplers[texture.sampler];
  85223. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  85224. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  85225. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  85226. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  85227. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  85228. var blob = new Blob([buffer]);
  85229. var blobURL = URL.createObjectURL(blob);
  85230. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  85231. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  85232. if (sampler.wrapS !== undefined) {
  85233. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  85234. }
  85235. if (sampler.wrapT !== undefined) {
  85236. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  85237. }
  85238. newTexture.name = id;
  85239. texture.babylonTexture = newTexture;
  85240. onSuccess(newTexture);
  85241. };
  85242. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  85243. var shader = gltfRuntime.shaders[id];
  85244. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  85245. var shaderString = atob(shader.uri.split(",")[1]);
  85246. onSuccess(shaderString);
  85247. }
  85248. else {
  85249. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  85250. if (request) {
  85251. onError(request.status + " " + request.statusText);
  85252. }
  85253. });
  85254. }
  85255. };
  85256. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  85257. var material = gltfRuntime.materials[id];
  85258. if (!material.technique) {
  85259. if (onError) {
  85260. onError("No technique found.");
  85261. }
  85262. return;
  85263. }
  85264. var technique = gltfRuntime.techniques[material.technique];
  85265. if (!technique) {
  85266. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  85267. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  85268. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  85269. onSuccess(defaultMaterial);
  85270. return;
  85271. }
  85272. var program = gltfRuntime.programs[technique.program];
  85273. var states = technique.states;
  85274. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  85275. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  85276. var newVertexShader = "";
  85277. var newPixelShader = "";
  85278. var vertexTokenizer = new Tokenizer(vertexShader);
  85279. var pixelTokenizer = new Tokenizer(pixelShader);
  85280. var unTreatedUniforms = {};
  85281. var uniforms = [];
  85282. var attributes = [];
  85283. var samplers = [];
  85284. // Fill uniform, sampler2D and attributes
  85285. for (var unif in technique.uniforms) {
  85286. var uniform = technique.uniforms[unif];
  85287. var uniformParameter = technique.parameters[uniform];
  85288. unTreatedUniforms[unif] = uniformParameter;
  85289. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  85290. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  85291. if (transformIndex !== -1) {
  85292. uniforms.push(babylonTransforms[transformIndex]);
  85293. delete unTreatedUniforms[unif];
  85294. }
  85295. else {
  85296. uniforms.push(unif);
  85297. }
  85298. }
  85299. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  85300. samplers.push(unif);
  85301. }
  85302. else {
  85303. uniforms.push(unif);
  85304. }
  85305. }
  85306. for (var attr in technique.attributes) {
  85307. var attribute = technique.attributes[attr];
  85308. var attributeParameter = technique.parameters[attribute];
  85309. if (attributeParameter.semantic) {
  85310. attributes.push(getAttribute(attributeParameter));
  85311. }
  85312. }
  85313. // Configure vertex shader
  85314. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  85315. var tokenType = vertexTokenizer.currentToken;
  85316. if (tokenType !== ETokenType.IDENTIFIER) {
  85317. newVertexShader += vertexTokenizer.currentString;
  85318. continue;
  85319. }
  85320. var foundAttribute = false;
  85321. for (var attr in technique.attributes) {
  85322. var attribute = technique.attributes[attr];
  85323. var attributeParameter = technique.parameters[attribute];
  85324. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  85325. newVertexShader += getAttribute(attributeParameter);
  85326. foundAttribute = true;
  85327. break;
  85328. }
  85329. }
  85330. if (foundAttribute) {
  85331. continue;
  85332. }
  85333. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  85334. }
  85335. // Configure pixel shader
  85336. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  85337. var tokenType = pixelTokenizer.currentToken;
  85338. if (tokenType !== ETokenType.IDENTIFIER) {
  85339. newPixelShader += pixelTokenizer.currentString;
  85340. continue;
  85341. }
  85342. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  85343. }
  85344. // Create shader material
  85345. var shaderPath = {
  85346. vertex: program.vertexShader + id,
  85347. fragment: program.fragmentShader + id
  85348. };
  85349. var options = {
  85350. attributes: attributes,
  85351. uniforms: uniforms,
  85352. samplers: samplers,
  85353. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  85354. };
  85355. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  85356. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  85357. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  85358. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  85359. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  85360. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  85361. if (states && states.functions) {
  85362. var functions = states.functions;
  85363. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  85364. shaderMaterial.backFaceCulling = false;
  85365. }
  85366. var blendFunc = functions.blendFuncSeparate;
  85367. if (blendFunc) {
  85368. 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) {
  85369. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  85370. }
  85371. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85372. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  85373. }
  85374. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85375. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  85376. }
  85377. 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) {
  85378. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  85379. }
  85380. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  85381. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  85382. }
  85383. 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) {
  85384. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  85385. }
  85386. }
  85387. }
  85388. };
  85389. return GLTFLoaderBase;
  85390. }());
  85391. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  85392. /**
  85393. * glTF V1 Loader
  85394. */
  85395. var GLTFLoader = /** @class */ (function () {
  85396. function GLTFLoader() {
  85397. // #region Stubs for IGLTFLoader interface
  85398. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  85399. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  85400. this.compileMaterials = false;
  85401. this.useClipPlane = false;
  85402. this.compileShadowGenerators = false;
  85403. this.onDisposeObservable = new BABYLON.Observable();
  85404. this.onMeshLoadedObservable = new BABYLON.Observable();
  85405. this.onTextureLoadedObservable = new BABYLON.Observable();
  85406. this.onMaterialLoadedObservable = new BABYLON.Observable();
  85407. this.onCompleteObservable = new BABYLON.Observable();
  85408. }
  85409. GLTFLoader.RegisterExtension = function (extension) {
  85410. if (GLTFLoader.Extensions[extension.name]) {
  85411. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  85412. return;
  85413. }
  85414. GLTFLoader.Extensions[extension.name] = extension;
  85415. };
  85416. GLTFLoader.prototype.dispose = function () { };
  85417. // #endregion
  85418. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  85419. var _this = this;
  85420. scene.useRightHandedSystem = true;
  85421. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  85422. gltfRuntime.importOnlyMeshes = true;
  85423. if (meshesNames === "") {
  85424. gltfRuntime.importMeshesNames = [];
  85425. }
  85426. else if (typeof meshesNames === "string") {
  85427. gltfRuntime.importMeshesNames = [meshesNames];
  85428. }
  85429. else if (meshesNames && !(meshesNames instanceof Array)) {
  85430. gltfRuntime.importMeshesNames = [meshesNames];
  85431. }
  85432. else {
  85433. gltfRuntime.importMeshesNames = [];
  85434. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  85435. }
  85436. // Create nodes
  85437. _this._createNodes(gltfRuntime);
  85438. var meshes = new Array();
  85439. var skeletons = new Array();
  85440. // Fill arrays of meshes and skeletons
  85441. for (var nde in gltfRuntime.nodes) {
  85442. var node = gltfRuntime.nodes[nde];
  85443. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  85444. meshes.push(node.babylonNode);
  85445. }
  85446. }
  85447. for (var skl in gltfRuntime.skins) {
  85448. var skin = gltfRuntime.skins[skl];
  85449. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  85450. skeletons.push(skin.babylonSkeleton);
  85451. }
  85452. }
  85453. // Load buffers, shaders, materials, etc.
  85454. _this._loadBuffersAsync(gltfRuntime, function () {
  85455. _this._loadShadersAsync(gltfRuntime, function () {
  85456. importMaterials(gltfRuntime);
  85457. postLoad(gltfRuntime);
  85458. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  85459. onSuccess(meshes, [], skeletons);
  85460. }
  85461. });
  85462. }, onProgress);
  85463. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  85464. onSuccess(meshes, [], skeletons);
  85465. }
  85466. }, onError);
  85467. return true;
  85468. };
  85469. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  85470. var _this = this;
  85471. scene.useRightHandedSystem = true;
  85472. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  85473. // Load runtime extensios
  85474. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  85475. // Create nodes
  85476. _this._createNodes(gltfRuntime);
  85477. // Load buffers, shaders, materials, etc.
  85478. _this._loadBuffersAsync(gltfRuntime, function () {
  85479. _this._loadShadersAsync(gltfRuntime, function () {
  85480. importMaterials(gltfRuntime);
  85481. postLoad(gltfRuntime);
  85482. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  85483. onSuccess();
  85484. }
  85485. });
  85486. });
  85487. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  85488. onSuccess();
  85489. }
  85490. }, onError);
  85491. }, onError);
  85492. };
  85493. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  85494. var hasShaders = false;
  85495. var processShader = function (sha, shader) {
  85496. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  85497. gltfRuntime.loadedShaderCount++;
  85498. if (shaderString) {
  85499. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  85500. }
  85501. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  85502. onload();
  85503. }
  85504. }, function () {
  85505. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  85506. });
  85507. };
  85508. for (var sha in gltfRuntime.shaders) {
  85509. hasShaders = true;
  85510. var shader = gltfRuntime.shaders[sha];
  85511. if (shader) {
  85512. processShader.bind(this, sha, shader)();
  85513. }
  85514. else {
  85515. BABYLON.Tools.Error("No shader named: " + sha);
  85516. }
  85517. }
  85518. if (!hasShaders) {
  85519. onload();
  85520. }
  85521. };
  85522. ;
  85523. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  85524. var hasBuffers = false;
  85525. var processBuffer = function (buf, buffer) {
  85526. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  85527. gltfRuntime.loadedBufferCount++;
  85528. if (bufferView) {
  85529. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  85530. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  85531. }
  85532. gltfRuntime.loadedBufferViews[buf] = bufferView;
  85533. }
  85534. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  85535. onLoad();
  85536. }
  85537. }, function () {
  85538. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  85539. });
  85540. };
  85541. for (var buf in gltfRuntime.buffers) {
  85542. hasBuffers = true;
  85543. var buffer = gltfRuntime.buffers[buf];
  85544. if (buffer) {
  85545. processBuffer.bind(this, buf, buffer)();
  85546. }
  85547. else {
  85548. BABYLON.Tools.Error("No buffer named: " + buf);
  85549. }
  85550. }
  85551. if (!hasBuffers) {
  85552. onLoad();
  85553. }
  85554. };
  85555. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  85556. var currentScene = gltfRuntime.currentScene;
  85557. if (currentScene) {
  85558. // Only one scene even if multiple scenes are defined
  85559. for (var i = 0; i < currentScene.nodes.length; i++) {
  85560. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85561. }
  85562. }
  85563. else {
  85564. // Load all scenes
  85565. for (var thing in gltfRuntime.scenes) {
  85566. currentScene = gltfRuntime.scenes[thing];
  85567. for (var i = 0; i < currentScene.nodes.length; i++) {
  85568. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  85569. }
  85570. }
  85571. }
  85572. };
  85573. GLTFLoader.Extensions = {};
  85574. return GLTFLoader;
  85575. }());
  85576. GLTF1.GLTFLoader = GLTFLoader;
  85577. ;
  85578. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  85579. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85580. })(BABYLON || (BABYLON = {}));
  85581. //# sourceMappingURL=babylon.glTFLoader.js.map
  85582. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85583. var BABYLON;
  85584. (function (BABYLON) {
  85585. var GLTF1;
  85586. (function (GLTF1) {
  85587. /**
  85588. * Utils functions for GLTF
  85589. */
  85590. var GLTFUtils = /** @class */ (function () {
  85591. function GLTFUtils() {
  85592. }
  85593. /**
  85594. * Sets the given "parameter" matrix
  85595. * @param scene: the {BABYLON.Scene} object
  85596. * @param source: the source node where to pick the matrix
  85597. * @param parameter: the GLTF technique parameter
  85598. * @param uniformName: the name of the shader's uniform
  85599. * @param shaderMaterial: the shader material
  85600. */
  85601. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  85602. var mat = null;
  85603. if (parameter.semantic === "MODEL") {
  85604. mat = source.getWorldMatrix();
  85605. }
  85606. else if (parameter.semantic === "PROJECTION") {
  85607. mat = scene.getProjectionMatrix();
  85608. }
  85609. else if (parameter.semantic === "VIEW") {
  85610. mat = scene.getViewMatrix();
  85611. }
  85612. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  85613. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  85614. }
  85615. else if (parameter.semantic === "MODELVIEW") {
  85616. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  85617. }
  85618. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  85619. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  85620. }
  85621. else if (parameter.semantic === "MODELINVERSE") {
  85622. mat = source.getWorldMatrix().invert();
  85623. }
  85624. else if (parameter.semantic === "VIEWINVERSE") {
  85625. mat = scene.getViewMatrix().invert();
  85626. }
  85627. else if (parameter.semantic === "PROJECTIONINVERSE") {
  85628. mat = scene.getProjectionMatrix().invert();
  85629. }
  85630. else if (parameter.semantic === "MODELVIEWINVERSE") {
  85631. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  85632. }
  85633. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  85634. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  85635. }
  85636. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  85637. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  85638. }
  85639. else {
  85640. debugger;
  85641. }
  85642. if (mat) {
  85643. switch (parameter.type) {
  85644. case GLTF1.EParameterType.FLOAT_MAT2:
  85645. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  85646. break;
  85647. case GLTF1.EParameterType.FLOAT_MAT3:
  85648. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  85649. break;
  85650. case GLTF1.EParameterType.FLOAT_MAT4:
  85651. shaderMaterial.setMatrix(uniformName, mat);
  85652. break;
  85653. default: break;
  85654. }
  85655. }
  85656. };
  85657. /**
  85658. * Sets the given "parameter" matrix
  85659. * @param shaderMaterial: the shader material
  85660. * @param uniform: the name of the shader's uniform
  85661. * @param value: the value of the uniform
  85662. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  85663. */
  85664. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  85665. switch (type) {
  85666. case GLTF1.EParameterType.FLOAT:
  85667. shaderMaterial.setFloat(uniform, value);
  85668. return true;
  85669. case GLTF1.EParameterType.FLOAT_VEC2:
  85670. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  85671. return true;
  85672. case GLTF1.EParameterType.FLOAT_VEC3:
  85673. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  85674. return true;
  85675. case GLTF1.EParameterType.FLOAT_VEC4:
  85676. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  85677. return true;
  85678. default: return false;
  85679. }
  85680. };
  85681. /**
  85682. * If the uri is a base64 string
  85683. * @param uri: the uri to test
  85684. */
  85685. GLTFUtils.IsBase64 = function (uri) {
  85686. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  85687. };
  85688. /**
  85689. * Decode the base64 uri
  85690. * @param uri: the uri to decode
  85691. */
  85692. GLTFUtils.DecodeBase64 = function (uri) {
  85693. var decodedString = atob(uri.split(",")[1]);
  85694. var bufferLength = decodedString.length;
  85695. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  85696. for (var i = 0; i < bufferLength; i++) {
  85697. bufferView[i] = decodedString.charCodeAt(i);
  85698. }
  85699. return bufferView.buffer;
  85700. };
  85701. /**
  85702. * Returns the wrap mode of the texture
  85703. * @param mode: the mode value
  85704. */
  85705. GLTFUtils.GetWrapMode = function (mode) {
  85706. switch (mode) {
  85707. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  85708. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  85709. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  85710. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  85711. }
  85712. };
  85713. /**
  85714. * Returns the byte stride giving an accessor
  85715. * @param accessor: the GLTF accessor objet
  85716. */
  85717. GLTFUtils.GetByteStrideFromType = function (accessor) {
  85718. // Needs this function since "byteStride" isn't requiered in glTF format
  85719. var type = accessor.type;
  85720. switch (type) {
  85721. case "VEC2": return 2;
  85722. case "VEC3": return 3;
  85723. case "VEC4": return 4;
  85724. case "MAT2": return 4;
  85725. case "MAT3": return 9;
  85726. case "MAT4": return 16;
  85727. default: return 1;
  85728. }
  85729. };
  85730. /**
  85731. * Returns the texture filter mode giving a mode value
  85732. * @param mode: the filter mode value
  85733. */
  85734. GLTFUtils.GetTextureFilterMode = function (mode) {
  85735. switch (mode) {
  85736. case GLTF1.ETextureFilterType.LINEAR:
  85737. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  85738. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  85739. case GLTF1.ETextureFilterType.NEAREST:
  85740. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  85741. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  85742. }
  85743. };
  85744. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  85745. var byteOffset = bufferView.byteOffset + byteOffset;
  85746. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  85747. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  85748. throw new Error("Buffer access is out of range");
  85749. }
  85750. var buffer = loadedBufferView.buffer;
  85751. byteOffset += loadedBufferView.byteOffset;
  85752. switch (componentType) {
  85753. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  85754. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  85755. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  85756. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  85757. default: return new Float32Array(buffer, byteOffset, byteLength);
  85758. }
  85759. };
  85760. /**
  85761. * Returns a buffer from its accessor
  85762. * @param gltfRuntime: the GLTF runtime
  85763. * @param accessor: the GLTF accessor
  85764. */
  85765. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  85766. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  85767. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  85768. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  85769. };
  85770. /**
  85771. * Decodes a buffer view into a string
  85772. * @param view: the buffer view
  85773. */
  85774. GLTFUtils.DecodeBufferToText = function (view) {
  85775. var result = "";
  85776. var length = view.byteLength;
  85777. for (var i = 0; i < length; ++i) {
  85778. result += String.fromCharCode(view[i]);
  85779. }
  85780. return result;
  85781. };
  85782. /**
  85783. * Returns the default material of gltf. Related to
  85784. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  85785. * @param scene: the Babylon.js scene
  85786. */
  85787. GLTFUtils.GetDefaultMaterial = function (scene) {
  85788. if (!GLTFUtils._DefaultMaterial) {
  85789. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  85790. "precision highp float;",
  85791. "",
  85792. "uniform mat4 worldView;",
  85793. "uniform mat4 projection;",
  85794. "",
  85795. "attribute vec3 position;",
  85796. "",
  85797. "void main(void)",
  85798. "{",
  85799. " gl_Position = projection * worldView * vec4(position, 1.0);",
  85800. "}"
  85801. ].join("\n");
  85802. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  85803. "precision highp float;",
  85804. "",
  85805. "uniform vec4 u_emission;",
  85806. "",
  85807. "void main(void)",
  85808. "{",
  85809. " gl_FragColor = u_emission;",
  85810. "}"
  85811. ].join("\n");
  85812. var shaderPath = {
  85813. vertex: "GLTFDefaultMaterial",
  85814. fragment: "GLTFDefaultMaterial"
  85815. };
  85816. var options = {
  85817. attributes: ["position"],
  85818. uniforms: ["worldView", "projection", "u_emission"],
  85819. samplers: new Array(),
  85820. needAlphaBlending: false
  85821. };
  85822. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  85823. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  85824. }
  85825. return GLTFUtils._DefaultMaterial;
  85826. };
  85827. // The GLTF default material
  85828. GLTFUtils._DefaultMaterial = null;
  85829. return GLTFUtils;
  85830. }());
  85831. GLTF1.GLTFUtils = GLTFUtils;
  85832. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85833. })(BABYLON || (BABYLON = {}));
  85834. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  85835. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85836. var BABYLON;
  85837. (function (BABYLON) {
  85838. var GLTF1;
  85839. (function (GLTF1) {
  85840. var GLTFLoaderExtension = /** @class */ (function () {
  85841. function GLTFLoaderExtension(name) {
  85842. this._name = name;
  85843. }
  85844. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  85845. get: function () {
  85846. return this._name;
  85847. },
  85848. enumerable: true,
  85849. configurable: true
  85850. });
  85851. /**
  85852. * Defines an override for loading the runtime
  85853. * Return true to stop further extensions from loading the runtime
  85854. */
  85855. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  85856. return false;
  85857. };
  85858. /**
  85859. * Defines an onverride for creating gltf runtime
  85860. * Return true to stop further extensions from creating the runtime
  85861. */
  85862. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  85863. return false;
  85864. };
  85865. /**
  85866. * Defines an override for loading buffers
  85867. * Return true to stop further extensions from loading this buffer
  85868. */
  85869. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  85870. return false;
  85871. };
  85872. /**
  85873. * Defines an override for loading texture buffers
  85874. * Return true to stop further extensions from loading this texture data
  85875. */
  85876. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  85877. return false;
  85878. };
  85879. /**
  85880. * Defines an override for creating textures
  85881. * Return true to stop further extensions from loading this texture
  85882. */
  85883. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  85884. return false;
  85885. };
  85886. /**
  85887. * Defines an override for loading shader strings
  85888. * Return true to stop further extensions from loading this shader data
  85889. */
  85890. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  85891. return false;
  85892. };
  85893. /**
  85894. * Defines an override for loading materials
  85895. * Return true to stop further extensions from loading this material
  85896. */
  85897. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  85898. return false;
  85899. };
  85900. // ---------
  85901. // Utilities
  85902. // ---------
  85903. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  85904. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  85905. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  85906. }, function () {
  85907. setTimeout(function () {
  85908. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  85909. });
  85910. });
  85911. };
  85912. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  85913. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  85914. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  85915. }, function () {
  85916. setTimeout(function () {
  85917. onSuccess();
  85918. });
  85919. });
  85920. };
  85921. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  85922. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  85923. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  85924. }, function () {
  85925. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  85926. });
  85927. };
  85928. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  85929. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  85930. };
  85931. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  85932. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  85933. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  85934. }, function () {
  85935. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  85936. });
  85937. };
  85938. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  85939. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  85940. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  85941. }, function () {
  85942. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  85943. });
  85944. };
  85945. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  85946. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  85947. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  85948. }, function () {
  85949. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  85950. });
  85951. };
  85952. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  85953. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  85954. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  85955. }, function () {
  85956. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  85957. });
  85958. };
  85959. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  85960. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  85961. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  85962. if (func(loaderExtension)) {
  85963. return;
  85964. }
  85965. }
  85966. defaultFunc();
  85967. };
  85968. return GLTFLoaderExtension;
  85969. }());
  85970. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  85971. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  85972. })(BABYLON || (BABYLON = {}));
  85973. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  85974. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  85975. var BABYLON;
  85976. (function (BABYLON) {
  85977. var GLTF1;
  85978. (function (GLTF1) {
  85979. var BinaryExtensionBufferName = "binary_glTF";
  85980. ;
  85981. ;
  85982. var GLTFBinaryExtension = /** @class */ (function (_super) {
  85983. __extends(GLTFBinaryExtension, _super);
  85984. function GLTFBinaryExtension() {
  85985. return _super.call(this, "KHR_binary_glTF") || this;
  85986. }
  85987. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  85988. var extensionsUsed = data.json.extensionsUsed;
  85989. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  85990. return false;
  85991. }
  85992. this._bin = data.bin;
  85993. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  85994. return true;
  85995. };
  85996. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  85997. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  85998. return false;
  85999. }
  86000. if (id !== BinaryExtensionBufferName) {
  86001. return false;
  86002. }
  86003. onSuccess(this._bin);
  86004. return true;
  86005. };
  86006. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  86007. var texture = gltfRuntime.textures[id];
  86008. var source = gltfRuntime.images[texture.source];
  86009. if (!source.extensions || !(this.name in source.extensions)) {
  86010. return false;
  86011. }
  86012. var sourceExt = source.extensions[this.name];
  86013. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  86014. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86015. onSuccess(buffer);
  86016. return true;
  86017. };
  86018. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  86019. var shader = gltfRuntime.shaders[id];
  86020. if (!shader.extensions || !(this.name in shader.extensions)) {
  86021. return false;
  86022. }
  86023. var binaryExtensionShader = shader.extensions[this.name];
  86024. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  86025. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  86026. setTimeout(function () {
  86027. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  86028. onSuccess(shaderString);
  86029. });
  86030. return true;
  86031. };
  86032. return GLTFBinaryExtension;
  86033. }(GLTF1.GLTFLoaderExtension));
  86034. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  86035. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  86036. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86037. })(BABYLON || (BABYLON = {}));
  86038. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  86039. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86040. var BABYLON;
  86041. (function (BABYLON) {
  86042. var GLTF1;
  86043. (function (GLTF1) {
  86044. ;
  86045. ;
  86046. ;
  86047. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  86048. __extends(GLTFMaterialsCommonExtension, _super);
  86049. function GLTFMaterialsCommonExtension() {
  86050. return _super.call(this, "KHR_materials_common") || this;
  86051. }
  86052. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  86053. if (!gltfRuntime.extensions)
  86054. return false;
  86055. var extension = gltfRuntime.extensions[this.name];
  86056. if (!extension)
  86057. return false;
  86058. // Create lights
  86059. var lights = extension.lights;
  86060. if (lights) {
  86061. for (var thing in lights) {
  86062. var light = lights[thing];
  86063. switch (light.type) {
  86064. case "ambient":
  86065. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  86066. var ambient = light.ambient;
  86067. if (ambient) {
  86068. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  86069. }
  86070. break;
  86071. case "point":
  86072. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  86073. var point = light.point;
  86074. if (point) {
  86075. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  86076. }
  86077. break;
  86078. case "directional":
  86079. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  86080. var directional = light.directional;
  86081. if (directional) {
  86082. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  86083. }
  86084. break;
  86085. case "spot":
  86086. var spot = light.spot;
  86087. if (spot) {
  86088. 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);
  86089. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  86090. }
  86091. break;
  86092. default:
  86093. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  86094. break;
  86095. }
  86096. }
  86097. }
  86098. return false;
  86099. };
  86100. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  86101. var material = gltfRuntime.materials[id];
  86102. if (!material || !material.extensions)
  86103. return false;
  86104. var extension = material.extensions[this.name];
  86105. if (!extension)
  86106. return false;
  86107. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  86108. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  86109. if (extension.technique === "CONSTANT") {
  86110. standardMaterial.disableLighting = true;
  86111. }
  86112. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  86113. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  86114. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  86115. // Ambient
  86116. if (typeof extension.values.ambient === "string") {
  86117. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  86118. }
  86119. else {
  86120. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  86121. }
  86122. // Diffuse
  86123. if (typeof extension.values.diffuse === "string") {
  86124. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  86125. }
  86126. else {
  86127. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  86128. }
  86129. // Emission
  86130. if (typeof extension.values.emission === "string") {
  86131. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  86132. }
  86133. else {
  86134. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  86135. }
  86136. // Specular
  86137. if (typeof extension.values.specular === "string") {
  86138. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  86139. }
  86140. else {
  86141. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  86142. }
  86143. return true;
  86144. };
  86145. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  86146. // Create buffer from texture url
  86147. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  86148. // Create texture from buffer
  86149. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  86150. }, onError);
  86151. };
  86152. return GLTFMaterialsCommonExtension;
  86153. }(GLTF1.GLTFLoaderExtension));
  86154. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  86155. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  86156. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  86157. })(BABYLON || (BABYLON = {}));
  86158. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  86159. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86160. var BABYLON;
  86161. (function (BABYLON) {
  86162. var GLTF2;
  86163. (function (GLTF2) {
  86164. /**
  86165. * Enums
  86166. */
  86167. var EComponentType;
  86168. (function (EComponentType) {
  86169. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  86170. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  86171. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  86172. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  86173. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  86174. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  86175. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  86176. var EMeshPrimitiveMode;
  86177. (function (EMeshPrimitiveMode) {
  86178. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  86179. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  86180. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  86181. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  86182. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  86183. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  86184. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  86185. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  86186. var ETextureMagFilter;
  86187. (function (ETextureMagFilter) {
  86188. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  86189. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  86190. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  86191. var ETextureMinFilter;
  86192. (function (ETextureMinFilter) {
  86193. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  86194. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  86195. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  86196. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  86197. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  86198. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  86199. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  86200. var ETextureWrapMode;
  86201. (function (ETextureWrapMode) {
  86202. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  86203. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  86204. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  86205. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  86206. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86207. })(BABYLON || (BABYLON = {}));
  86208. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  86209. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86210. var BABYLON;
  86211. (function (BABYLON) {
  86212. var GLTF2;
  86213. (function (GLTF2) {
  86214. var GLTFLoaderTracker = /** @class */ (function () {
  86215. function GLTFLoaderTracker(onComplete) {
  86216. this._pendingCount = 0;
  86217. this._callback = onComplete;
  86218. }
  86219. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  86220. this._pendingCount++;
  86221. };
  86222. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  86223. if (--this._pendingCount === 0) {
  86224. this._callback();
  86225. }
  86226. };
  86227. return GLTFLoaderTracker;
  86228. }());
  86229. var GLTFLoader = /** @class */ (function () {
  86230. function GLTFLoader() {
  86231. this._disposed = false;
  86232. this._defaultSampler = {};
  86233. this._renderReady = false;
  86234. this._requests = new Array();
  86235. this._renderReadyObservable = new BABYLON.Observable();
  86236. // Count of pending work that needs to complete before the asset is rendered.
  86237. this._renderPendingCount = 0;
  86238. // Count of pending work that needs to complete before the loader is disposed.
  86239. this._loaderPendingCount = 0;
  86240. this._loaderTrackers = new Array();
  86241. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  86242. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  86243. this.compileMaterials = false;
  86244. this.useClipPlane = false;
  86245. this.compileShadowGenerators = false;
  86246. this.onDisposeObservable = new BABYLON.Observable();
  86247. this.onMeshLoadedObservable = new BABYLON.Observable();
  86248. this.onTextureLoadedObservable = new BABYLON.Observable();
  86249. this.onMaterialLoadedObservable = new BABYLON.Observable();
  86250. this.onCompleteObservable = new BABYLON.Observable();
  86251. }
  86252. GLTFLoader.RegisterExtension = function (extension) {
  86253. if (GLTFLoader.Extensions[extension.name]) {
  86254. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  86255. return;
  86256. }
  86257. GLTFLoader.Extensions[extension.name] = extension;
  86258. // Keep the order of registration so that extensions registered first are called first.
  86259. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  86260. };
  86261. GLTFLoader.prototype.dispose = function () {
  86262. if (this._disposed) {
  86263. return;
  86264. }
  86265. this._disposed = true;
  86266. this._abortRequests();
  86267. this._releaseResources();
  86268. this.onDisposeObservable.notifyObservers(this);
  86269. };
  86270. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  86271. var _this = this;
  86272. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  86273. if (onSuccess) {
  86274. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  86275. }
  86276. }, onProgress, onError);
  86277. };
  86278. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  86279. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  86280. };
  86281. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  86282. var _this = this;
  86283. this._babylonScene = scene;
  86284. this._rootUrl = rootUrl;
  86285. this._successCallback = onSuccess;
  86286. this._progressCallback = onProgress;
  86287. this._errorCallback = onError;
  86288. this._tryCatchOnError(function () {
  86289. _this._loadData(data);
  86290. _this._addPendingData(_this);
  86291. _this._loadDefaultScene(nodeNames);
  86292. _this._loadAnimations();
  86293. _this._removePendingData(_this);
  86294. });
  86295. };
  86296. GLTFLoader.prototype._onProgress = function () {
  86297. if (!this._progressCallback) {
  86298. return;
  86299. }
  86300. var lengthComputable = true;
  86301. var loaded = 0;
  86302. var total = 0;
  86303. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  86304. var request = _a[_i];
  86305. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  86306. return;
  86307. }
  86308. lengthComputable = lengthComputable && request._lengthComputable;
  86309. loaded += request._loaded;
  86310. total += request._total;
  86311. }
  86312. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  86313. };
  86314. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  86315. if (this._renderReady) {
  86316. func();
  86317. }
  86318. else {
  86319. this._renderReadyObservable.add(func);
  86320. }
  86321. };
  86322. GLTFLoader.prototype._onRenderReady = function () {
  86323. this._rootNode.babylonMesh.setEnabled(true);
  86324. this._startAnimations();
  86325. if (this._successCallback) {
  86326. this._successCallback();
  86327. }
  86328. this._renderReadyObservable.notifyObservers(this);
  86329. };
  86330. GLTFLoader.prototype._onComplete = function () {
  86331. this._abortRequests();
  86332. this._releaseResources();
  86333. this.onCompleteObservable.notifyObservers(this);
  86334. };
  86335. GLTFLoader.prototype._loadData = function (data) {
  86336. this._gltf = data.json;
  86337. // Assign the index of each object for convinience.
  86338. GLTFLoader._AssignIndices(this._gltf.accessors);
  86339. GLTFLoader._AssignIndices(this._gltf.animations);
  86340. GLTFLoader._AssignIndices(this._gltf.buffers);
  86341. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  86342. GLTFLoader._AssignIndices(this._gltf.images);
  86343. GLTFLoader._AssignIndices(this._gltf.materials);
  86344. GLTFLoader._AssignIndices(this._gltf.meshes);
  86345. GLTFLoader._AssignIndices(this._gltf.nodes);
  86346. GLTFLoader._AssignIndices(this._gltf.samplers);
  86347. GLTFLoader._AssignIndices(this._gltf.scenes);
  86348. GLTFLoader._AssignIndices(this._gltf.skins);
  86349. GLTFLoader._AssignIndices(this._gltf.textures);
  86350. if (data.bin) {
  86351. var buffers = this._gltf.buffers;
  86352. if (buffers && buffers[0] && !buffers[0].uri) {
  86353. var binaryBuffer = buffers[0];
  86354. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  86355. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  86356. }
  86357. binaryBuffer.loadedData = data.bin;
  86358. }
  86359. else {
  86360. BABYLON.Tools.Warn("Unexpected BIN chunk");
  86361. }
  86362. }
  86363. };
  86364. GLTFLoader.prototype._getMeshes = function () {
  86365. var meshes = new Array();
  86366. // Root mesh is always first.
  86367. meshes.push(this._rootNode.babylonMesh);
  86368. var nodes = this._gltf.nodes;
  86369. if (nodes) {
  86370. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  86371. var node = nodes_1[_i];
  86372. if (node.babylonMesh) {
  86373. meshes.push(node.babylonMesh);
  86374. }
  86375. }
  86376. }
  86377. return meshes;
  86378. };
  86379. GLTFLoader.prototype._getSkeletons = function () {
  86380. var skeletons = new Array();
  86381. var skins = this._gltf.skins;
  86382. if (skins) {
  86383. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  86384. var skin = skins_1[_i];
  86385. if (skin.babylonSkeleton) {
  86386. skeletons.push(skin.babylonSkeleton);
  86387. }
  86388. }
  86389. }
  86390. return skeletons;
  86391. };
  86392. GLTFLoader.prototype._startAnimations = function () {
  86393. var animations = this._gltf.animations;
  86394. if (!animations) {
  86395. return;
  86396. }
  86397. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  86398. var animation = animations_1[_i];
  86399. animation.babylonAnimationGroup.normalize();
  86400. }
  86401. switch (this.animationStartMode) {
  86402. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  86403. // do nothing
  86404. break;
  86405. }
  86406. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  86407. var animation = animations[0];
  86408. animation.babylonAnimationGroup.start(true);
  86409. break;
  86410. }
  86411. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  86412. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  86413. var animation = animations_2[_a];
  86414. animation.babylonAnimationGroup.start(true);
  86415. }
  86416. break;
  86417. }
  86418. default: {
  86419. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  86420. return;
  86421. }
  86422. }
  86423. };
  86424. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  86425. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  86426. if (!scene) {
  86427. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  86428. }
  86429. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  86430. };
  86431. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  86432. var _this = this;
  86433. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  86434. switch (this.coordinateSystemMode) {
  86435. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  86436. if (!this._babylonScene.useRightHandedSystem) {
  86437. this._rootNode.rotation = [0, 1, 0, 0];
  86438. this._rootNode.scale = [1, 1, -1];
  86439. this._loadTransform(this._rootNode);
  86440. }
  86441. break;
  86442. }
  86443. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  86444. this._babylonScene.useRightHandedSystem = true;
  86445. break;
  86446. }
  86447. default: {
  86448. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  86449. return;
  86450. }
  86451. }
  86452. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  86453. var nodeIndices = scene.nodes;
  86454. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  86455. node.parent = parentNode;
  86456. return true;
  86457. }, this._rootNode);
  86458. if (nodeNames) {
  86459. if (!(nodeNames instanceof Array)) {
  86460. nodeNames = [nodeNames];
  86461. }
  86462. var filteredNodeIndices_1 = new Array();
  86463. this._traverseNodes(context, nodeIndices, function (node) {
  86464. if (nodeNames.indexOf(node.name) !== -1) {
  86465. filteredNodeIndices_1.push(node.index);
  86466. node.parent = _this._rootNode;
  86467. return false;
  86468. }
  86469. return true;
  86470. }, this._rootNode);
  86471. nodeIndices = filteredNodeIndices_1;
  86472. }
  86473. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  86474. var index = nodeIndices_1[_i];
  86475. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86476. if (!node) {
  86477. throw new Error(context + ": Failed to find node " + index);
  86478. }
  86479. this._loadNode("#/nodes/" + index, node);
  86480. }
  86481. // Disable the root mesh until the asset is ready to render.
  86482. this._rootNode.babylonMesh.setEnabled(false);
  86483. };
  86484. GLTFLoader.prototype._loadNode = function (context, node) {
  86485. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  86486. return;
  86487. }
  86488. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  86489. this._loadTransform(node);
  86490. if (node.mesh != null) {
  86491. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  86492. if (!mesh) {
  86493. throw new Error(context + ": Failed to find mesh " + node.mesh);
  86494. }
  86495. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  86496. }
  86497. node.babylonMesh.parent = node.parent.babylonMesh;
  86498. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  86499. node.babylonAnimationTargets.push(node.babylonMesh);
  86500. if (node.skin != null) {
  86501. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  86502. if (!skin_1) {
  86503. throw new Error(context + ": Failed to find skin " + node.skin);
  86504. }
  86505. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  86506. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  86507. node.babylonMesh._refreshBoundingInfo(true);
  86508. });
  86509. node.babylonMesh.parent = this._rootNode.babylonMesh;
  86510. node.babylonMesh.position = BABYLON.Vector3.Zero();
  86511. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  86512. node.babylonMesh.scaling = BABYLON.Vector3.One();
  86513. }
  86514. if (node.camera != null) {
  86515. // TODO: handle cameras
  86516. }
  86517. if (node.children) {
  86518. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  86519. var index = _a[_i];
  86520. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86521. if (!childNode) {
  86522. throw new Error(context + ": Failed to find child node " + index);
  86523. }
  86524. this._loadNode("#/nodes/" + index, childNode);
  86525. }
  86526. }
  86527. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  86528. };
  86529. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  86530. var _this = this;
  86531. var primitives = mesh.primitives;
  86532. if (!primitives || primitives.length === 0) {
  86533. throw new Error(context + ": Primitives are missing");
  86534. }
  86535. this._createMorphTargets(context, node, mesh);
  86536. this._loadAllVertexDataAsync(context, mesh, function () {
  86537. _this._loadMorphTargets(context, node, mesh);
  86538. var vertexData = new BABYLON.VertexData();
  86539. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  86540. var primitive = primitives_1[_i];
  86541. vertexData.merge(primitive.vertexData);
  86542. }
  86543. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  86544. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  86545. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  86546. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  86547. node.babylonMesh.subMeshes = [];
  86548. var verticesStart = 0;
  86549. var indicesStart = 0;
  86550. for (var index = 0; index < primitives.length; index++) {
  86551. var vertexData_1 = primitives[index].vertexData;
  86552. var verticesCount = vertexData_1.positions.length;
  86553. var indicesCount = vertexData_1.indices.length;
  86554. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  86555. verticesStart += verticesCount;
  86556. indicesStart += indicesCount;
  86557. }
  86558. ;
  86559. });
  86560. if (primitives.length === 1) {
  86561. var primitive = primitives[0];
  86562. if (primitive.material == null) {
  86563. node.babylonMesh.material = this._getDefaultMaterial();
  86564. }
  86565. else {
  86566. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  86567. if (!material) {
  86568. throw new Error(context + ": Failed to find material " + primitive.material);
  86569. }
  86570. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  86571. if (isNew) {
  86572. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  86573. }
  86574. node.babylonMesh.material = babylonMaterial;
  86575. });
  86576. }
  86577. }
  86578. else {
  86579. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  86580. node.babylonMesh.material = multiMaterial;
  86581. var subMaterials_1 = multiMaterial.subMaterials;
  86582. var _loop_1 = function (index) {
  86583. var primitive = primitives[index];
  86584. if (primitive.material == null) {
  86585. subMaterials_1[index] = this_1._getDefaultMaterial();
  86586. }
  86587. else {
  86588. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  86589. if (!material) {
  86590. throw new Error(context + ": Failed to find material " + primitive.material);
  86591. }
  86592. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  86593. if (isNew) {
  86594. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  86595. }
  86596. subMaterials_1[index] = babylonMaterial;
  86597. });
  86598. }
  86599. };
  86600. var this_1 = this;
  86601. for (var index = 0; index < primitives.length; index++) {
  86602. _loop_1(index);
  86603. }
  86604. ;
  86605. }
  86606. };
  86607. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  86608. var primitives = mesh.primitives;
  86609. var numRemainingPrimitives = primitives.length;
  86610. var _loop_2 = function (index) {
  86611. var primitive = primitives[index];
  86612. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  86613. primitive.vertexData = vertexData;
  86614. if (--numRemainingPrimitives === 0) {
  86615. onSuccess();
  86616. }
  86617. });
  86618. };
  86619. var this_2 = this;
  86620. for (var index = 0; index < primitives.length; index++) {
  86621. _loop_2(index);
  86622. }
  86623. };
  86624. /**
  86625. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  86626. * @param {ArrayBufferView} data
  86627. * @param {IGLTFAccessor} accessor
  86628. */
  86629. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  86630. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  86631. return data;
  86632. }
  86633. var buffer = data;
  86634. var factor = 1;
  86635. switch (accessor.componentType) {
  86636. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  86637. factor = 1 / 255;
  86638. break;
  86639. }
  86640. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  86641. factor = 1 / 65535;
  86642. break;
  86643. }
  86644. default: {
  86645. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  86646. }
  86647. }
  86648. var result = new Float32Array(accessor.count * 2);
  86649. for (var i = 0; i < result.length; ++i) {
  86650. result[i] = buffer[i] * factor;
  86651. }
  86652. return result;
  86653. };
  86654. /**
  86655. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  86656. * @param {ArrayBufferView} data
  86657. * @param {IGLTFAccessor} accessor
  86658. */
  86659. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  86660. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  86661. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  86662. return data;
  86663. }
  86664. var buffer = data;
  86665. var factor = 1;
  86666. switch (accessor.componentType) {
  86667. case GLTF2.EComponentType.FLOAT: {
  86668. factor = 1;
  86669. break;
  86670. }
  86671. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  86672. factor = 1 / 255;
  86673. break;
  86674. }
  86675. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  86676. factor = 1 / 65535;
  86677. break;
  86678. }
  86679. default: {
  86680. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  86681. }
  86682. }
  86683. var result = new Float32Array(accessor.count * 4);
  86684. if (colorComponentCount === 4) {
  86685. for (var i = 0; i < result.length; ++i) {
  86686. result[i] = buffer[i] * factor;
  86687. }
  86688. }
  86689. else {
  86690. var offset = 0;
  86691. for (var i = 0; i < result.length; ++i) {
  86692. if ((i + 1) % 4 === 0) {
  86693. result[i] = 1;
  86694. }
  86695. else {
  86696. result[i] = buffer[offset++] * factor;
  86697. }
  86698. }
  86699. }
  86700. return result;
  86701. };
  86702. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  86703. var _this = this;
  86704. var attributes = primitive.attributes;
  86705. if (!attributes) {
  86706. throw new Error(context + ": Attributes are missing");
  86707. }
  86708. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  86709. // TODO: handle other primitive modes
  86710. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  86711. }
  86712. var vertexData = new BABYLON.VertexData();
  86713. var numRemainingAttributes = Object.keys(attributes).length;
  86714. var _loop_3 = function (attribute) {
  86715. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  86716. if (!accessor) {
  86717. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  86718. }
  86719. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  86720. switch (attribute) {
  86721. case "POSITION": {
  86722. vertexData.positions = data;
  86723. break;
  86724. }
  86725. case "NORMAL": {
  86726. vertexData.normals = data;
  86727. break;
  86728. }
  86729. case "TANGENT": {
  86730. vertexData.tangents = data;
  86731. break;
  86732. }
  86733. case "TEXCOORD_0": {
  86734. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  86735. break;
  86736. }
  86737. case "TEXCOORD_1": {
  86738. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  86739. break;
  86740. }
  86741. case "JOINTS_0": {
  86742. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  86743. break;
  86744. }
  86745. case "WEIGHTS_0": {
  86746. //TODO: need to add support for normalized weights.
  86747. vertexData.matricesWeights = data;
  86748. break;
  86749. }
  86750. case "COLOR_0": {
  86751. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  86752. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  86753. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  86754. mesh.hasVertexAlpha = hasVertexAlpha;
  86755. }
  86756. break;
  86757. }
  86758. default: {
  86759. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  86760. break;
  86761. }
  86762. }
  86763. if (--numRemainingAttributes === 0) {
  86764. if (primitive.indices == null) {
  86765. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  86766. for (var i = 0; i < vertexData.indices.length; i++) {
  86767. vertexData.indices[i] = i;
  86768. }
  86769. onSuccess(vertexData);
  86770. }
  86771. else {
  86772. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  86773. if (!indicesAccessor) {
  86774. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  86775. }
  86776. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  86777. vertexData.indices = data;
  86778. onSuccess(vertexData);
  86779. });
  86780. }
  86781. }
  86782. });
  86783. };
  86784. var this_3 = this;
  86785. for (var attribute in attributes) {
  86786. _loop_3(attribute);
  86787. }
  86788. };
  86789. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  86790. var primitives = mesh.primitives;
  86791. var targets = primitives[0].targets;
  86792. if (!targets) {
  86793. return;
  86794. }
  86795. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  86796. var primitive = primitives_2[_i];
  86797. if (!primitive.targets || primitive.targets.length != targets.length) {
  86798. throw new Error(context + ": All primitives are required to list the same number of targets");
  86799. }
  86800. }
  86801. var morphTargetManager = new BABYLON.MorphTargetManager();
  86802. node.babylonMesh.morphTargetManager = morphTargetManager;
  86803. for (var index = 0; index < targets.length; index++) {
  86804. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  86805. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  86806. }
  86807. };
  86808. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  86809. var morphTargetManager = node.babylonMesh.morphTargetManager;
  86810. if (!morphTargetManager) {
  86811. return;
  86812. }
  86813. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  86814. var numTargets = morphTargetManager.numTargets;
  86815. for (var index = 0; index < numTargets; index++) {
  86816. var vertexData = new BABYLON.VertexData();
  86817. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  86818. var primitive = _a[_i];
  86819. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  86820. }
  86821. if (!vertexData.positions) {
  86822. throw new Error(context + ": Positions are missing");
  86823. }
  86824. var target = morphTargetManager.getTarget(index);
  86825. target.setPositions(vertexData.positions);
  86826. target.setNormals(vertexData.normals);
  86827. target.setTangents(vertexData.tangents);
  86828. }
  86829. });
  86830. };
  86831. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  86832. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  86833. var _loop_4 = function (primitive) {
  86834. var targets = primitive.targets;
  86835. primitive.targetsVertexData = new Array(targets.length);
  86836. var _loop_5 = function (index) {
  86837. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  86838. primitive.targetsVertexData[index] = vertexData;
  86839. if (--numRemainingTargets === 0) {
  86840. onSuccess();
  86841. }
  86842. });
  86843. };
  86844. for (var index = 0; index < targets.length; index++) {
  86845. _loop_5(index);
  86846. }
  86847. };
  86848. var this_4 = this;
  86849. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  86850. var primitive = _a[_i];
  86851. _loop_4(primitive);
  86852. }
  86853. };
  86854. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  86855. var targetVertexData = new BABYLON.VertexData();
  86856. var numRemainingAttributes = Object.keys(attributes).length;
  86857. var _loop_6 = function (attribute) {
  86858. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  86859. if (!accessor) {
  86860. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  86861. }
  86862. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  86863. // glTF stores morph target information as deltas while babylon.js expects the final data.
  86864. // As a result we have to add the original data to the delta to calculate the final data.
  86865. var values = data;
  86866. switch (attribute) {
  86867. case "POSITION": {
  86868. for (var i = 0; i < values.length; i++) {
  86869. values[i] += vertexData.positions[i];
  86870. }
  86871. targetVertexData.positions = values;
  86872. break;
  86873. }
  86874. case "NORMAL": {
  86875. for (var i = 0; i < values.length; i++) {
  86876. values[i] += vertexData.normals[i];
  86877. }
  86878. targetVertexData.normals = values;
  86879. break;
  86880. }
  86881. case "TANGENT": {
  86882. // Tangent data for morph targets is stored as xyz delta.
  86883. // The vertexData.tangent is stored as xyzw.
  86884. // So we need to skip every fourth vertexData.tangent.
  86885. for (var i = 0, j = 0; i < values.length; i++, j++) {
  86886. values[i] += vertexData.tangents[j];
  86887. if ((i + 1) % 3 == 0) {
  86888. j++;
  86889. }
  86890. }
  86891. targetVertexData.tangents = values;
  86892. break;
  86893. }
  86894. default: {
  86895. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  86896. break;
  86897. }
  86898. }
  86899. if (--numRemainingAttributes === 0) {
  86900. onSuccess(targetVertexData);
  86901. }
  86902. });
  86903. };
  86904. var this_5 = this;
  86905. for (var attribute in attributes) {
  86906. _loop_6(attribute);
  86907. }
  86908. };
  86909. GLTFLoader.prototype._loadTransform = function (node) {
  86910. var position = BABYLON.Vector3.Zero();
  86911. var rotation = BABYLON.Quaternion.Identity();
  86912. var scaling = BABYLON.Vector3.One();
  86913. if (node.matrix) {
  86914. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  86915. matrix.decompose(scaling, rotation, position);
  86916. }
  86917. else {
  86918. if (node.translation)
  86919. position = BABYLON.Vector3.FromArray(node.translation);
  86920. if (node.rotation)
  86921. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  86922. if (node.scale)
  86923. scaling = BABYLON.Vector3.FromArray(node.scale);
  86924. }
  86925. node.babylonMesh.position = position;
  86926. node.babylonMesh.rotationQuaternion = rotation;
  86927. node.babylonMesh.scaling = scaling;
  86928. };
  86929. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  86930. var _this = this;
  86931. if (skin.babylonSkeleton) {
  86932. onSuccess();
  86933. return;
  86934. }
  86935. var skeletonId = "skeleton" + skin.index;
  86936. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  86937. if (skin.inverseBindMatrices == null) {
  86938. this._loadBones(context, skin, null);
  86939. onSuccess();
  86940. }
  86941. else {
  86942. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  86943. if (!accessor) {
  86944. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  86945. }
  86946. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  86947. _this._loadBones(context, skin, data);
  86948. onSuccess();
  86949. });
  86950. }
  86951. };
  86952. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  86953. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  86954. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  86955. node.babylonAnimationTargets.push(babylonBone);
  86956. return babylonBone;
  86957. };
  86958. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  86959. var babylonBones = {};
  86960. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  86961. var index = _a[_i];
  86962. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86963. if (!node) {
  86964. throw new Error(context + ": Failed to find joint " + index);
  86965. }
  86966. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  86967. }
  86968. };
  86969. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  86970. var babylonBone = babylonBones[node.index];
  86971. if (babylonBone) {
  86972. return babylonBone;
  86973. }
  86974. var boneIndex = skin.joints.indexOf(node.index);
  86975. var baseMatrix = BABYLON.Matrix.Identity();
  86976. if (inverseBindMatrixData && boneIndex !== -1) {
  86977. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  86978. baseMatrix.invertToRef(baseMatrix);
  86979. }
  86980. var babylonParentBone = null;
  86981. if (node.parent !== this._rootNode) {
  86982. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  86983. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  86984. }
  86985. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  86986. babylonBones[node.index] = babylonBone;
  86987. return babylonBone;
  86988. };
  86989. GLTFLoader.prototype._getNodeMatrix = function (node) {
  86990. return node.matrix ?
  86991. BABYLON.Matrix.FromArray(node.matrix) :
  86992. 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());
  86993. };
  86994. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  86995. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  86996. var index = indices_1[_i];
  86997. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  86998. if (!node) {
  86999. throw new Error(context + ": Failed to find node " + index);
  87000. }
  87001. this._traverseNode(context, node, action, parentNode);
  87002. }
  87003. };
  87004. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  87005. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  87006. return;
  87007. }
  87008. if (!action(node, parentNode)) {
  87009. return;
  87010. }
  87011. if (node.children) {
  87012. this._traverseNodes(context, node.children, action, node);
  87013. }
  87014. };
  87015. GLTFLoader.prototype._loadAnimations = function () {
  87016. var animations = this._gltf.animations;
  87017. if (!animations) {
  87018. return;
  87019. }
  87020. for (var index = 0; index < animations.length; index++) {
  87021. var animation = animations[index];
  87022. this._loadAnimation("#/animations/" + index, animation);
  87023. }
  87024. };
  87025. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  87026. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  87027. for (var index = 0; index < animation.channels.length; index++) {
  87028. var channel = GLTFLoader._GetProperty(animation.channels, index);
  87029. if (!channel) {
  87030. throw new Error(context + ": Failed to find channel " + index);
  87031. }
  87032. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  87033. if (!sampler) {
  87034. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  87035. }
  87036. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  87037. }
  87038. };
  87039. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  87040. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  87041. if (!targetNode) {
  87042. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  87043. }
  87044. var targetPath;
  87045. var animationType;
  87046. switch (channel.target.path) {
  87047. case "translation": {
  87048. targetPath = "position";
  87049. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87050. break;
  87051. }
  87052. case "rotation": {
  87053. targetPath = "rotationQuaternion";
  87054. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  87055. break;
  87056. }
  87057. case "scale": {
  87058. targetPath = "scaling";
  87059. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  87060. break;
  87061. }
  87062. case "weights": {
  87063. targetPath = "influence";
  87064. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  87065. break;
  87066. }
  87067. default: {
  87068. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  87069. }
  87070. }
  87071. var inputData;
  87072. var outputData;
  87073. var checkSuccess = function () {
  87074. if (!inputData || !outputData) {
  87075. return;
  87076. }
  87077. var outputBufferOffset = 0;
  87078. var getNextOutputValue;
  87079. switch (targetPath) {
  87080. case "position": {
  87081. getNextOutputValue = function () {
  87082. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87083. outputBufferOffset += 3;
  87084. return value;
  87085. };
  87086. break;
  87087. }
  87088. case "rotationQuaternion": {
  87089. getNextOutputValue = function () {
  87090. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  87091. outputBufferOffset += 4;
  87092. return value;
  87093. };
  87094. break;
  87095. }
  87096. case "scaling": {
  87097. getNextOutputValue = function () {
  87098. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  87099. outputBufferOffset += 3;
  87100. return value;
  87101. };
  87102. break;
  87103. }
  87104. case "influence": {
  87105. getNextOutputValue = function () {
  87106. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  87107. var value = new Array(numTargets);
  87108. for (var i = 0; i < numTargets; i++) {
  87109. value[i] = outputData[outputBufferOffset++];
  87110. }
  87111. return value;
  87112. };
  87113. break;
  87114. }
  87115. }
  87116. sampler.interpolation = sampler.interpolation || "LINEAR";
  87117. var getNextKey;
  87118. switch (sampler.interpolation) {
  87119. case "STEP": {
  87120. getNextKey = function (frameIndex) { return ({
  87121. frame: inputData[frameIndex],
  87122. value: getNextOutputValue(),
  87123. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  87124. }); };
  87125. break;
  87126. }
  87127. case "LINEAR": {
  87128. getNextKey = function (frameIndex) { return ({
  87129. frame: inputData[frameIndex],
  87130. value: getNextOutputValue()
  87131. }); };
  87132. break;
  87133. }
  87134. case "CUBICSPLINE": {
  87135. getNextKey = function (frameIndex) { return ({
  87136. frame: inputData[frameIndex],
  87137. inTangent: getNextOutputValue(),
  87138. value: getNextOutputValue(),
  87139. outTangent: getNextOutputValue()
  87140. }); };
  87141. break;
  87142. }
  87143. default: {
  87144. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  87145. }
  87146. }
  87147. ;
  87148. var keys;
  87149. if (inputData.length === 1) {
  87150. var key = getNextKey(0);
  87151. keys = [
  87152. { frame: key.frame, value: key.value },
  87153. { frame: key.frame + 1, value: key.value }
  87154. ];
  87155. }
  87156. else {
  87157. keys = new Array(inputData.length);
  87158. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  87159. keys[frameIndex] = getNextKey(frameIndex);
  87160. }
  87161. }
  87162. if (targetPath === "influence") {
  87163. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  87164. var _loop_7 = function (targetIndex) {
  87165. var morphTarget = morphTargetManager.getTarget(targetIndex);
  87166. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87167. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87168. babylonAnimation.setKeys(keys.map(function (key) { return ({
  87169. frame: key.frame,
  87170. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  87171. value: key.value[targetIndex],
  87172. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  87173. }); }));
  87174. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  87175. };
  87176. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  87177. _loop_7(targetIndex);
  87178. }
  87179. }
  87180. else {
  87181. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  87182. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  87183. babylonAnimation.setKeys(keys);
  87184. if (targetNode.babylonAnimationTargets) {
  87185. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  87186. var target = _a[_i];
  87187. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  87188. }
  87189. }
  87190. }
  87191. };
  87192. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  87193. if (!inputAccessor) {
  87194. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  87195. }
  87196. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  87197. inputData = data;
  87198. checkSuccess();
  87199. });
  87200. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  87201. if (!outputAccessor) {
  87202. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  87203. }
  87204. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  87205. outputData = data;
  87206. checkSuccess();
  87207. });
  87208. };
  87209. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  87210. var _this = this;
  87211. this._addPendingData(buffer);
  87212. if (buffer.loadedData) {
  87213. onSuccess(buffer.loadedData);
  87214. this._removePendingData(buffer);
  87215. }
  87216. else if (buffer.loadedObservable) {
  87217. buffer.loadedObservable.add(function (buffer) {
  87218. onSuccess(buffer.loadedData);
  87219. _this._removePendingData(buffer);
  87220. });
  87221. }
  87222. else {
  87223. if (!buffer.uri) {
  87224. throw new Error(context + ": Uri is missing");
  87225. }
  87226. buffer.loadedObservable = new BABYLON.Observable();
  87227. buffer.loadedObservable.add(function (buffer) {
  87228. onSuccess(buffer.loadedData);
  87229. _this._removePendingData(buffer);
  87230. });
  87231. this._loadUriAsync(context, buffer.uri, function (data) {
  87232. buffer.loadedData = data;
  87233. buffer.loadedObservable.notifyObservers(buffer);
  87234. buffer.loadedObservable = undefined;
  87235. });
  87236. }
  87237. };
  87238. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  87239. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  87240. if (!buffer) {
  87241. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  87242. }
  87243. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  87244. var data;
  87245. try {
  87246. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  87247. }
  87248. catch (e) {
  87249. throw new Error(context + ": " + e.message);
  87250. }
  87251. onSuccess(data);
  87252. });
  87253. };
  87254. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  87255. var _this = this;
  87256. if (accessor.sparse) {
  87257. throw new Error(context + ": Sparse accessors are not currently supported");
  87258. }
  87259. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  87260. if (!bufferView) {
  87261. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  87262. }
  87263. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  87264. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  87265. var data;
  87266. var byteOffset = accessor.byteOffset || 0;
  87267. var byteStride = bufferView.byteStride;
  87268. if (byteStride === 0) {
  87269. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  87270. }
  87271. try {
  87272. switch (accessor.componentType) {
  87273. case GLTF2.EComponentType.BYTE: {
  87274. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87275. break;
  87276. }
  87277. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  87278. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87279. break;
  87280. }
  87281. case GLTF2.EComponentType.SHORT: {
  87282. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87283. break;
  87284. }
  87285. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  87286. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87287. break;
  87288. }
  87289. case GLTF2.EComponentType.UNSIGNED_INT: {
  87290. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87291. break;
  87292. }
  87293. case GLTF2.EComponentType.FLOAT: {
  87294. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  87295. break;
  87296. }
  87297. default: {
  87298. throw new Error(context + ": Invalid component type " + accessor.componentType);
  87299. }
  87300. }
  87301. }
  87302. catch (e) {
  87303. throw new Error(context + ": " + e);
  87304. }
  87305. onSuccess(data);
  87306. });
  87307. };
  87308. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  87309. byteOffset += data.byteOffset;
  87310. var targetLength = count * numComponents;
  87311. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  87312. return new typedArray(data.buffer, byteOffset, targetLength);
  87313. }
  87314. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  87315. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  87316. var targetBuffer = new typedArray(targetLength);
  87317. var sourceIndex = 0;
  87318. var targetIndex = 0;
  87319. while (targetIndex < targetLength) {
  87320. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  87321. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  87322. targetIndex++;
  87323. }
  87324. sourceIndex += elementStride;
  87325. }
  87326. return targetBuffer;
  87327. };
  87328. GLTFLoader.prototype._addPendingData = function (data) {
  87329. if (!this._renderReady) {
  87330. this._renderPendingCount++;
  87331. }
  87332. this._addLoaderPendingData(data);
  87333. };
  87334. GLTFLoader.prototype._removePendingData = function (data) {
  87335. var _this = this;
  87336. if (!this._renderReady) {
  87337. if (--this._renderPendingCount === 0) {
  87338. this._addLoaderPendingData(this);
  87339. this._compileMaterialsAsync(function () {
  87340. _this._compileShadowGeneratorsAsync(function () {
  87341. _this._removeLoaderPendingData(_this);
  87342. _this._renderReady = true;
  87343. _this._onRenderReady();
  87344. });
  87345. });
  87346. }
  87347. }
  87348. this._removeLoaderPendingData(data);
  87349. };
  87350. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  87351. this._loaderPendingCount++;
  87352. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  87353. var tracker = _a[_i];
  87354. tracker._addPendingData(data);
  87355. }
  87356. };
  87357. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  87358. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  87359. var tracker = _a[_i];
  87360. tracker._removePendingData(data);
  87361. }
  87362. if (--this._loaderPendingCount === 0) {
  87363. this._onComplete();
  87364. }
  87365. };
  87366. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  87367. var _this = this;
  87368. var tracker = new GLTFLoaderTracker(function () {
  87369. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  87370. onComplete();
  87371. });
  87372. this._loaderTrackers.push(tracker);
  87373. this._addLoaderPendingData(tracker);
  87374. action();
  87375. this._removeLoaderPendingData(tracker);
  87376. };
  87377. GLTFLoader.prototype._getDefaultMaterial = function () {
  87378. if (!this._defaultMaterial) {
  87379. var id = "__gltf_default";
  87380. var material = this._babylonScene.getMaterialByName(id);
  87381. if (!material) {
  87382. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  87383. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  87384. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  87385. material.metallic = 1;
  87386. material.roughness = 1;
  87387. }
  87388. this._defaultMaterial = material;
  87389. }
  87390. return this._defaultMaterial;
  87391. };
  87392. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  87393. var babylonMaterial = material.babylonMaterial;
  87394. // Ensure metallic workflow
  87395. babylonMaterial.metallic = 1;
  87396. babylonMaterial.roughness = 1;
  87397. var properties = material.pbrMetallicRoughness;
  87398. if (!properties) {
  87399. return;
  87400. }
  87401. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  87402. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  87403. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  87404. if (properties.baseColorTexture) {
  87405. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  87406. if (!texture) {
  87407. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  87408. }
  87409. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  87410. }
  87411. if (properties.metallicRoughnessTexture) {
  87412. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  87413. if (!texture) {
  87414. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  87415. }
  87416. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  87417. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  87418. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  87419. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  87420. }
  87421. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  87422. };
  87423. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  87424. if (material.babylonMaterial) {
  87425. assign(material.babylonMaterial, false);
  87426. return;
  87427. }
  87428. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  87429. return;
  87430. }
  87431. this._createPbrMaterial(material);
  87432. this._loadMaterialBaseProperties(context, material);
  87433. this._loadMaterialMetallicRoughnessProperties(context, material);
  87434. assign(material.babylonMaterial, true);
  87435. };
  87436. GLTFLoader.prototype._createPbrMaterial = function (material) {
  87437. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  87438. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  87439. material.babylonMaterial = babylonMaterial;
  87440. };
  87441. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  87442. var babylonMaterial = material.babylonMaterial;
  87443. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  87444. if (material.doubleSided) {
  87445. babylonMaterial.backFaceCulling = false;
  87446. babylonMaterial.twoSidedLighting = true;
  87447. }
  87448. if (material.normalTexture) {
  87449. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  87450. if (!texture) {
  87451. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  87452. }
  87453. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  87454. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  87455. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  87456. if (material.normalTexture.scale != null) {
  87457. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  87458. }
  87459. }
  87460. if (material.occlusionTexture) {
  87461. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  87462. if (!texture) {
  87463. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  87464. }
  87465. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  87466. babylonMaterial.useAmbientInGrayScale = true;
  87467. if (material.occlusionTexture.strength != null) {
  87468. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  87469. }
  87470. }
  87471. if (material.emissiveTexture) {
  87472. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  87473. if (!texture) {
  87474. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  87475. }
  87476. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  87477. }
  87478. };
  87479. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  87480. var babylonMaterial = material.babylonMaterial;
  87481. var alphaMode = material.alphaMode || "OPAQUE";
  87482. switch (alphaMode) {
  87483. case "OPAQUE": {
  87484. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  87485. break;
  87486. }
  87487. case "MASK": {
  87488. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  87489. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  87490. if (colorFactor) {
  87491. if (colorFactor[3] == 0) {
  87492. babylonMaterial.alphaCutOff = 1;
  87493. }
  87494. else {
  87495. babylonMaterial.alphaCutOff /= colorFactor[3];
  87496. }
  87497. }
  87498. if (babylonMaterial.albedoTexture) {
  87499. babylonMaterial.albedoTexture.hasAlpha = true;
  87500. }
  87501. break;
  87502. }
  87503. case "BLEND": {
  87504. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  87505. if (colorFactor) {
  87506. babylonMaterial.alpha = colorFactor[3];
  87507. }
  87508. if (babylonMaterial.albedoTexture) {
  87509. babylonMaterial.albedoTexture.hasAlpha = true;
  87510. babylonMaterial.useAlphaFromAlbedoTexture = true;
  87511. }
  87512. break;
  87513. }
  87514. default: {
  87515. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  87516. }
  87517. }
  87518. };
  87519. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  87520. var _this = this;
  87521. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  87522. if (!sampler) {
  87523. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  87524. }
  87525. this._loadSampler("#/samplers/" + sampler.index, sampler);
  87526. this._addPendingData(texture);
  87527. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  87528. _this._tryCatchOnError(function () {
  87529. _this._removePendingData(texture);
  87530. });
  87531. }, function (message) {
  87532. _this._tryCatchOnError(function () {
  87533. throw new Error(context + ": " + message);
  87534. });
  87535. });
  87536. if (texture.url) {
  87537. babylonTexture.updateURL(texture.url);
  87538. }
  87539. else if (texture.dataReadyObservable) {
  87540. texture.dataReadyObservable.add(function (texture) {
  87541. babylonTexture.updateURL(texture.url);
  87542. });
  87543. }
  87544. else {
  87545. texture.dataReadyObservable = new BABYLON.Observable();
  87546. texture.dataReadyObservable.add(function (texture) {
  87547. babylonTexture.updateURL(texture.url);
  87548. });
  87549. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  87550. if (!image_1) {
  87551. throw new Error(context + ": Failed to find source " + texture.source);
  87552. }
  87553. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  87554. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  87555. texture.dataReadyObservable.notifyObservers(texture);
  87556. texture.dataReadyObservable = undefined;
  87557. });
  87558. }
  87559. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  87560. babylonTexture.wrapU = sampler.wrapU;
  87561. babylonTexture.wrapV = sampler.wrapV;
  87562. babylonTexture.name = texture.name || "texture" + texture.index;
  87563. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  87564. return babylonTexture;
  87565. };
  87566. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  87567. if (sampler.noMipMaps != undefined) {
  87568. return;
  87569. }
  87570. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  87571. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  87572. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  87573. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  87574. };
  87575. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  87576. if (image.uri) {
  87577. this._loadUriAsync(context, image.uri, onSuccess);
  87578. }
  87579. else {
  87580. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  87581. if (!bufferView) {
  87582. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  87583. }
  87584. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  87585. }
  87586. };
  87587. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  87588. var _this = this;
  87589. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  87590. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  87591. return;
  87592. }
  87593. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  87594. throw new Error(context + ": Uri '" + uri + "' is invalid");
  87595. }
  87596. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  87597. _this._tryCatchOnError(function () {
  87598. onSuccess(new Uint8Array(data));
  87599. });
  87600. }, function (event) {
  87601. _this._tryCatchOnError(function () {
  87602. if (request && !_this._renderReady) {
  87603. request._lengthComputable = event.lengthComputable;
  87604. request._loaded = event.loaded;
  87605. request._total = event.total;
  87606. _this._onProgress();
  87607. }
  87608. });
  87609. }, this._babylonScene.database, true, function (request, exception) {
  87610. _this._tryCatchOnError(function () {
  87611. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  87612. });
  87613. });
  87614. this._requests.push(request);
  87615. };
  87616. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  87617. if (this._disposed) {
  87618. return;
  87619. }
  87620. try {
  87621. handler();
  87622. }
  87623. catch (e) {
  87624. BABYLON.Tools.Error("glTF Loader: " + e.message);
  87625. if (this._errorCallback) {
  87626. this._errorCallback(e.message, e);
  87627. }
  87628. this.dispose();
  87629. }
  87630. };
  87631. GLTFLoader._AssignIndices = function (array) {
  87632. if (array) {
  87633. for (var index = 0; index < array.length; index++) {
  87634. array[index].index = index;
  87635. }
  87636. }
  87637. };
  87638. GLTFLoader._GetProperty = function (array, index) {
  87639. if (!array || index == undefined || !array[index]) {
  87640. return null;
  87641. }
  87642. return array[index];
  87643. };
  87644. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  87645. // Set defaults if undefined
  87646. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  87647. switch (mode) {
  87648. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  87649. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  87650. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  87651. default:
  87652. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  87653. return BABYLON.Texture.WRAP_ADDRESSMODE;
  87654. }
  87655. };
  87656. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  87657. // Set defaults if undefined
  87658. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  87659. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  87660. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  87661. switch (minFilter) {
  87662. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  87663. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  87664. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  87665. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  87666. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  87667. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  87668. default:
  87669. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  87670. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  87671. }
  87672. }
  87673. else {
  87674. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  87675. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  87676. }
  87677. switch (minFilter) {
  87678. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  87679. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  87680. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  87681. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  87682. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  87683. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  87684. default:
  87685. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  87686. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  87687. }
  87688. }
  87689. };
  87690. GLTFLoader._GetNumComponents = function (context, type) {
  87691. switch (type) {
  87692. case "SCALAR": return 1;
  87693. case "VEC2": return 2;
  87694. case "VEC3": return 3;
  87695. case "VEC4": return 4;
  87696. case "MAT2": return 4;
  87697. case "MAT3": return 9;
  87698. case "MAT4": return 16;
  87699. }
  87700. throw new Error(context + ": Invalid type " + type);
  87701. };
  87702. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  87703. var _this = this;
  87704. if (this.useClipPlane) {
  87705. babylonMaterial.forceCompilation(babylonMesh, function () {
  87706. babylonMaterial.forceCompilation(babylonMesh, function () {
  87707. _this._tryCatchOnError(onSuccess);
  87708. }, { clipPlane: true });
  87709. });
  87710. }
  87711. else {
  87712. babylonMaterial.forceCompilation(babylonMesh, function () {
  87713. _this._tryCatchOnError(onSuccess);
  87714. });
  87715. }
  87716. };
  87717. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  87718. if (!this.compileMaterials || !this._gltf.materials) {
  87719. onSuccess();
  87720. return;
  87721. }
  87722. var meshes = this._getMeshes();
  87723. var remaining = 0;
  87724. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  87725. var mesh = meshes_1[_i];
  87726. if (mesh.material instanceof BABYLON.MultiMaterial) {
  87727. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  87728. var subMaterial = _b[_a];
  87729. if (subMaterial) {
  87730. remaining++;
  87731. }
  87732. }
  87733. }
  87734. else if (mesh.material) {
  87735. remaining++;
  87736. }
  87737. }
  87738. if (remaining === 0) {
  87739. onSuccess();
  87740. return;
  87741. }
  87742. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  87743. var mesh = meshes_2[_c];
  87744. if (mesh.material instanceof BABYLON.MultiMaterial) {
  87745. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  87746. var subMaterial = _e[_d];
  87747. if (subMaterial) {
  87748. this._compileMaterialAsync(subMaterial, mesh, function () {
  87749. if (--remaining === 0) {
  87750. onSuccess();
  87751. }
  87752. });
  87753. }
  87754. }
  87755. }
  87756. else if (mesh.material) {
  87757. this._compileMaterialAsync(mesh.material, mesh, function () {
  87758. if (--remaining === 0) {
  87759. onSuccess();
  87760. }
  87761. });
  87762. }
  87763. }
  87764. };
  87765. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  87766. var _this = this;
  87767. if (!this.compileShadowGenerators) {
  87768. onSuccess();
  87769. return;
  87770. }
  87771. var lights = this._babylonScene.lights;
  87772. var remaining = 0;
  87773. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  87774. var light = lights_1[_i];
  87775. var generator = light.getShadowGenerator();
  87776. if (generator) {
  87777. remaining++;
  87778. }
  87779. }
  87780. if (remaining === 0) {
  87781. onSuccess();
  87782. return;
  87783. }
  87784. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  87785. var light = lights_2[_a];
  87786. var generator = light.getShadowGenerator();
  87787. if (generator) {
  87788. generator.forceCompilation(function () {
  87789. if (--remaining === 0) {
  87790. _this._tryCatchOnError(onSuccess);
  87791. }
  87792. });
  87793. }
  87794. }
  87795. };
  87796. GLTFLoader.prototype._abortRequests = function () {
  87797. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  87798. var request = _a[_i];
  87799. request.abort();
  87800. }
  87801. this._requests.length = 0;
  87802. };
  87803. GLTFLoader.prototype._releaseResources = function () {
  87804. if (this._gltf.textures) {
  87805. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  87806. var texture = _a[_i];
  87807. if (texture.url) {
  87808. URL.revokeObjectURL(texture.url);
  87809. texture.url = undefined;
  87810. }
  87811. }
  87812. }
  87813. };
  87814. GLTFLoader.Extensions = {};
  87815. return GLTFLoader;
  87816. }());
  87817. GLTF2.GLTFLoader = GLTFLoader;
  87818. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  87819. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  87820. })(BABYLON || (BABYLON = {}));
  87821. //# sourceMappingURL=babylon.glTFLoader.js.map
  87822. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87823. var BABYLON;
  87824. (function (BABYLON) {
  87825. var GLTF2;
  87826. (function (GLTF2) {
  87827. /**
  87828. * Utils functions for GLTF
  87829. */
  87830. var GLTFUtils = /** @class */ (function () {
  87831. function GLTFUtils() {
  87832. }
  87833. /**
  87834. * If the uri is a base64 string
  87835. * @param uri: the uri to test
  87836. */
  87837. GLTFUtils.IsBase64 = function (uri) {
  87838. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  87839. };
  87840. /**
  87841. * Decode the base64 uri
  87842. * @param uri: the uri to decode
  87843. */
  87844. GLTFUtils.DecodeBase64 = function (uri) {
  87845. var decodedString = atob(uri.split(",")[1]);
  87846. var bufferLength = decodedString.length;
  87847. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  87848. for (var i = 0; i < bufferLength; i++) {
  87849. bufferView[i] = decodedString.charCodeAt(i);
  87850. }
  87851. return bufferView.buffer;
  87852. };
  87853. GLTFUtils.ValidateUri = function (uri) {
  87854. return (uri.indexOf("..") === -1);
  87855. };
  87856. return GLTFUtils;
  87857. }());
  87858. GLTF2.GLTFUtils = GLTFUtils;
  87859. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  87860. })(BABYLON || (BABYLON = {}));
  87861. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  87862. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  87863. var BABYLON;
  87864. (function (BABYLON) {
  87865. var GLTF2;
  87866. (function (GLTF2) {
  87867. var GLTFLoaderExtension = /** @class */ (function () {
  87868. function GLTFLoaderExtension() {
  87869. this.enabled = true;
  87870. }
  87871. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  87872. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  87873. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  87874. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  87875. var _this = this;
  87876. if (!property.extensions) {
  87877. return false;
  87878. }
  87879. var extension = property.extensions[this.name];
  87880. if (!extension) {
  87881. return false;
  87882. }
  87883. // Clear out the extension before executing the action to avoid recursing into the same property.
  87884. property.extensions[this.name] = undefined;
  87885. action(context + "extensions/" + this.name, extension, function () {
  87886. // Restore the extension after completing the action.
  87887. property.extensions[_this.name] = extension;
  87888. });
  87889. return true;
  87890. };
  87891. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  87892. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  87893. };
  87894. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  87895. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  87896. };
  87897. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  87898. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  87899. };
  87900. GLTFLoaderExtension._ApplyExtensions = function (action) {
  87901. var extensions = GLTFLoaderExtension._Extensions;
  87902. if (!extensions) {
  87903. return false;
  87904. }
  87905. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  87906. var extension = extensions_1[_i];
  87907. if (extension.enabled && action(extension)) {
  87908. return true;
  87909. }
  87910. }
  87911. return false;
  87912. };
  87913. //
  87914. // Utilities
  87915. //
  87916. GLTFLoaderExtension._Extensions = [];
  87917. return GLTFLoaderExtension;
  87918. }());
  87919. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  87920. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  87921. })(BABYLON || (BABYLON = {}));
  87922. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  87923. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  87924. var BABYLON;
  87925. (function (BABYLON) {
  87926. var GLTF2;
  87927. (function (GLTF2) {
  87928. var Extensions;
  87929. (function (Extensions) {
  87930. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  87931. var MSFTLOD = /** @class */ (function (_super) {
  87932. __extends(MSFTLOD, _super);
  87933. function MSFTLOD() {
  87934. var _this = _super !== null && _super.apply(this, arguments) || this;
  87935. /**
  87936. * Specify the minimal delay between LODs in ms (default = 250)
  87937. */
  87938. _this.Delay = 250;
  87939. return _this;
  87940. }
  87941. Object.defineProperty(MSFTLOD.prototype, "name", {
  87942. get: function () {
  87943. return "MSFT_lod";
  87944. },
  87945. enumerable: true,
  87946. configurable: true
  87947. });
  87948. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  87949. return this._loadExtension(context, node, function (context, extension, onComplete) {
  87950. for (var i = extension.ids.length - 1; i >= 0; i--) {
  87951. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  87952. if (!lodNode) {
  87953. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  87954. }
  87955. loader._traverseNode(context, lodNode, action, parentNode);
  87956. }
  87957. loader._traverseNode(context, node, action, parentNode);
  87958. onComplete();
  87959. });
  87960. };
  87961. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  87962. var _this = this;
  87963. return this._loadExtension(context, node, function (context, extension, onComplete) {
  87964. var nodes = [node];
  87965. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  87966. var index = _a[_i];
  87967. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  87968. if (!lodNode) {
  87969. throw new Error(context + ": Failed to find node " + index);
  87970. }
  87971. nodes.push(lodNode);
  87972. }
  87973. loader._addLoaderPendingData(node);
  87974. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  87975. loader._removeLoaderPendingData(node);
  87976. onComplete();
  87977. });
  87978. });
  87979. };
  87980. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  87981. var _this = this;
  87982. loader._whenAction(function () {
  87983. loader._loadNode(context, nodes[index]);
  87984. }, function () {
  87985. if (index !== nodes.length - 1) {
  87986. var previousNode = nodes[index + 1];
  87987. previousNode.babylonMesh.setEnabled(false);
  87988. }
  87989. if (index === 0) {
  87990. onComplete();
  87991. return;
  87992. }
  87993. setTimeout(function () {
  87994. loader._tryCatchOnError(function () {
  87995. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  87996. });
  87997. }, _this.Delay);
  87998. });
  87999. };
  88000. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  88001. var _this = this;
  88002. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88003. var materials = [material];
  88004. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  88005. var index = _a[_i];
  88006. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  88007. if (!lodMaterial) {
  88008. throw new Error(context + ": Failed to find material " + index);
  88009. }
  88010. materials.push(lodMaterial);
  88011. }
  88012. loader._addLoaderPendingData(material);
  88013. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  88014. loader._removeLoaderPendingData(material);
  88015. onComplete();
  88016. });
  88017. });
  88018. };
  88019. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  88020. var _this = this;
  88021. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  88022. if (index === materials.length - 1) {
  88023. assign(babylonMaterial, isNew);
  88024. // Load the next LOD when the loader is ready to render.
  88025. loader._executeWhenRenderReady(function () {
  88026. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88027. });
  88028. }
  88029. else {
  88030. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  88031. assign(babylonMaterial, isNew);
  88032. if (index === 0) {
  88033. onComplete();
  88034. }
  88035. else {
  88036. setTimeout(function () {
  88037. loader._tryCatchOnError(function () {
  88038. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  88039. });
  88040. }, _this.Delay);
  88041. }
  88042. });
  88043. }
  88044. });
  88045. };
  88046. return MSFTLOD;
  88047. }(GLTF2.GLTFLoaderExtension));
  88048. Extensions.MSFTLOD = MSFTLOD;
  88049. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  88050. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88051. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88052. })(BABYLON || (BABYLON = {}));
  88053. //# sourceMappingURL=MSFT_lod.js.map
  88054. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  88055. var BABYLON;
  88056. (function (BABYLON) {
  88057. var GLTF2;
  88058. (function (GLTF2) {
  88059. var Extensions;
  88060. (function (Extensions) {
  88061. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  88062. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  88063. function KHRMaterialsPbrSpecularGlossiness() {
  88064. return _super !== null && _super.apply(this, arguments) || this;
  88065. }
  88066. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  88067. get: function () {
  88068. return "KHR_materials_pbrSpecularGlossiness";
  88069. },
  88070. enumerable: true,
  88071. configurable: true
  88072. });
  88073. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  88074. var _this = this;
  88075. return this._loadExtension(context, material, function (context, extension, onComplete) {
  88076. loader._createPbrMaterial(material);
  88077. loader._loadMaterialBaseProperties(context, material);
  88078. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  88079. assign(material.babylonMaterial, true);
  88080. onComplete();
  88081. });
  88082. };
  88083. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  88084. var babylonMaterial = material.babylonMaterial;
  88085. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  88086. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  88087. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  88088. if (properties.diffuseTexture) {
  88089. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  88090. if (!texture) {
  88091. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  88092. }
  88093. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  88094. }
  88095. if (properties.specularGlossinessTexture) {
  88096. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  88097. if (!texture) {
  88098. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  88099. }
  88100. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  88101. babylonMaterial.reflectivityTexture.hasAlpha = true;
  88102. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  88103. }
  88104. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  88105. };
  88106. return KHRMaterialsPbrSpecularGlossiness;
  88107. }(GLTF2.GLTFLoaderExtension));
  88108. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  88109. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  88110. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  88111. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  88112. })(BABYLON || (BABYLON = {}));
  88113. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  88114. (function universalModuleDefinition(root, factory) {
  88115. var f = factory();
  88116. if (root && root["BABYLON"]) {
  88117. return;
  88118. }
  88119. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  88120. globalObject["BABYLON"] = f;
  88121. if(typeof exports === 'object' && typeof module === 'object')
  88122. module.exports = f;
  88123. else if(typeof define === 'function' && define.amd)
  88124. define(["BABYLON"], factory);
  88125. else if(typeof exports === 'object')
  88126. exports["BABYLON"] = f;
  88127. else {
  88128. root["BABYLON"] = f;
  88129. }
  88130. })(this, function() {
  88131. return BABYLON;
  88132. });